I need to highlight and get the word under the mouse pointer when i press the right click in a QTextBrowser. I already implemented the showContextMenu function for the QTextBrowser for the right mouse click thing. However i can't highlight the word under the mouse pointer and extract it. I found the following solution online:
QTextCursor tc = txtBrwsr->textCursor();
tc.select(QTextCursor::WordUnderCursor);
QString word = tc.selectedText();
However, it is not working and the word is empty, my aim behind this is to get the word and highlight it even if the user didn't highlight the word before pressing the right mouse click.
Any help is appreciated.
textCursor() function returns a copy of the QTextCursor.
You need call setTextCursor() after all changes.
That's example of how to highlight word under mouse cursor after right button click.
MyTextBrowser.h
class MyTextBrowser : public QTextBrowser {
// ...
protected:
void mousePressEvent(QMouseEvent *mouseEvent);
// ...
};
MyTextBrowser.cpp
void MyTextBrowser::mousePressEvent(QMouseEvent *mouseEvent) {
if (Qt::RightButton == mouseEvent->button()) {
QTextCursor textCursor = cursorForPosition(mouseEvent->pos());
textCursor.select(QTextCursor::WordUnderCursor);
setTextCursor(textCursor);
QString word = textCursor.selectedText();
qDebug() << word;
}
QTextBrowser::mousePressEvent(mouseEvent);
}
Good luck.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With