Clickable hyperlink in QTextEdit

Kha Tran picture Kha Tran · Mar 8, 2016 · Viewed 8k times · Source

I want to use QTextEdit (in read-only mode) to show a clickable hyperlink, I used to do

QTextEdit *textEdit = new QTextEdit;
QTextCursor cursor(textEdit->document());
textEdit->setTextCursor(cursor);
cursor->insertHtml("<a href=\"www.google.com\" >Google</a>");
textEdit->show();

this code will show Google as hyperlink but unable to click.
And if I used

QTextEdit *textEdit = new QTextEdit;
QTextCursor cursor(textEdit->document());
textEdit->setTextCursor(cursor);
QTextCharFormat linkFormat = cursor.charFormat();
linkFormat.setAnchor(true);
linkFormat.setAnchorHref("http://www.google.com");
linkFormat.setAnchorName("Google");
cursor.insertText("Google", linkFormat);

then nothing happen. "Google" is just normal text.

Please help me insert clickable hyperlink to QTextEdit.

Answer

Fabio picture Fabio · Mar 8, 2016

Using QTextBrowser is simpler (as suggested by another answer). However, if for some reason you want to use QTextEdit, try to change the text interaction flags using setTextInteractionFlags(). I think you have to enable the Qt::LinksAccessibleByMouse flag.

See Qt::TextInteractionFlag and QTextEdit::textInteractionFlags