QPlainTextEdit and anchors
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:
Code:
...
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);
}
}
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
Re: QPlainTextEdit and anchors
does the highlighting even show up? did you enable mouse tracking? could you also post the code of your mouseMoveEvent?
Re: QPlainTextEdit and anchors
Hi
I've solved it in a rather cumbersome way where I use cursorForPosition() to manually sweep each QTextBlock for a URL.
Here is basically what I do:
Code:
{
int cursor_pos = cursorForPosition(e->pos()).position();
int block_pos = block.position();
QVector<int> url_index, url_length;
int index = 0;
do
{
int length = 0;
url = urlFound(text, index, length);
if(url.size())
{
url_index.push_back(index);
url_length.push_back(length);
urls.push_back(url);
}
index += length;
}
while(url.size());
url.clear();
for(int i=0;i<url_index.size();i++)
{
if(cursor_pos >= block_pos+url_index[i] &&
cursor_pos < block_pos+url_index[i]+url_length[i])
{
url = urls[i];
break;
}
}
return url;
}
-- Bjoern