Hi
I'm using a QPlainTextEdit for text chat and would like to highlight URLs. I do this by subclassing QSyntaxHighlighter and call setFormat() like this:
...
void highlightBlock(const QString& text)
{
QString pattern
= "(http://[^ ]+)";
int index = text.indexOf(expression);
while (index >= 0) {
int length = expression.matchedLength();
myClassFormat.setFontUnderline(true);
myClassFormat.setForeground(Qt::blue);
myClassFormat.setAnchor(true);
myClassFormat.setAnchorHref(expression.cap(1));
myClassFormat.setAnchorName(expression.cap(1));
setFormat(index, length, myClassFormat);
index = text.indexOf(expression, index + length);
}
}
class UrlSyntaxHighlighter : public QSyntaxHighlighter
...
void highlightBlock(const QString& text)
{
QString pattern = "(http://[^ ]+)";
QRegExp expression(pattern);
int index = text.indexOf(expression);
while (index >= 0) {
int length = expression.matchedLength();
QTextCharFormat myClassFormat = format(index);
myClassFormat.setFontUnderline(true);
myClassFormat.setForeground(Qt::blue);
myClassFormat.setAnchor(true);
myClassFormat.setAnchorHref(expression.cap(1));
myClassFormat.setAnchorName(expression.cap(1));
setFormat(index, length, myClassFormat);
index = text.indexOf(expression, index + length);
}
}
To copy to clipboard, switch view to plain text mode
In my QPlainTextEdit I'm then overriding mouseMoveEvent(.) to change the mouse cursor when the anchor is hovered. However, when I access the QTextCursor using QPlainTextEdit::cursorForPosition(.) and extract the QTextCharFormat there is no anchor set on the text. Anyone know why?
Btw, I know I can use QTextEdit instead which has better support for anchors but I try and keep memory low and I don't need all the fancy picture-stuff. Also I'm aware that the regex isn't entirely correct.
-- Bjoern
Bookmarks