PDA

View Full Version : QPlainTextEdit and anchors



bear101
6th December 2009, 17:07
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:



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);
}
}


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

fullmetalcoder
13th December 2009, 12:01
does the highlighting even show up? did you enable mouse tracking? could you also post the code of your mouseMoveEvent?

bear101
13th December 2009, 18:10
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:



QString ChatTextEdit::currentUrl(QMouseEvent* e) const
{
QTextDocument* doc = document();

int cursor_pos = cursorForPosition(e->pos()).position();
QTextBlock block = doc->findBlock(cursor_pos);
int block_pos = block.position();

QString text = block.text();

QVector<int> url_index, url_length;
QStringList urls;

int index = 0;
QString url;
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