Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTextEdit: get word under the mouse pointer

I made this CompileOutput class, and basically what I want is when I click the word, it emits signal selectedWord, and when I hover over words, I want it to emit signal hoveredWord.

The mousePressEvent works, but enterEvent wont work. When I hover over words, nothing happens.

This is my chunk of code:

CompileOutput::CompileOutput(QWidget *parent): QTextEdit(parent)
{
    setReadOnly(true);
}
CompileOutput::~CompileOutput()
{
}

void CompileOutput::mousePressEvent(QMouseEvent * event)
{
    QTextCursor tc = cursorForPosition ( event->pos());
    tc.select(QTextCursor::LineUnderCursor);
    QString strWord = tc.selectedText();

    if(!strWord.isEmpty())
    {

        emit selectedWord(strWord);
    }
}

void CompileOutput::enterEvent(QMouseEvent *event)
{
    QTextCursor tc = cursorForPosition(event->pos());
    tc.select(QTextCursor::LineUnderCursor);
    QString strWord = tc.selectedText();

    qDebug() << strWord;
    if(strWord=="the line i need.")
    {
        emit hoveredWord(); //this signal makes cursor shape change while over right line of text
    }

}
like image 500
djidara696 Avatar asked Dec 14 '25 18:12

djidara696


1 Answers

Try this:

In the constructor add

setMouseTracking(true);

and then use mouseMoveEvent instead of enterEvent

like image 93
finmor Avatar answered Dec 17 '25 08:12

finmor



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!