Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Word under mouse pointer in Qt

Tags:

qt

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.

like image 916
Ameen Avatar asked Dec 31 '25 09:12

Ameen


1 Answers

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.

like image 153
aleks_misyuk Avatar answered Jan 03 '26 22:01

aleks_misyuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!