Ggicci
Ggicci

Reputation: 825

Qt how to insert html into an editable QWebView at the cursor position?

I'm trying to use QWebView to implement a blog post editor. And I have some sample html snippets to insert into the editor by triggering menu actions. However, it's not convenient as QTextEdit to insert html. As for why I don't use QTextEdit, see my test code following:

QTextEdit *edit = new QTextEdit;
edit->insertHtml(tr("<div class=\"gci-hello\">Hello</div>"));
qDebug() << edit->toHtml(); // --> the div tag disappeared

So, if I use QWebView, the div tag will be reserved. But I can't find out how to insert my snippet at the cursor postion on the view.

Upvotes: 2

Views: 1716

Answers (1)

Daniel V&#233;rit&#233;
Daniel V&#233;rit&#233;

Reputation: 61506

Use execCommand with InsertHTML :

QString html = "<div>Some text</div>";
QString js = QString("document.execCommand('InsertHTML',false,'%1');").arg(html);
webview->page()->mainFrame()->evaluateJavaScript(js);

And if there are single quote characters in the HTML snippet, make sure you quote them with a backslash, since the snippet is injected through a JS string.

Upvotes: 2

Related Questions