smrkelj smrkelj - 4 days ago 5
C++ Question

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
}

}

Answer

Try this:

In the constructor add

setMouseTracking(true);

and then use mouseMoveEvent instead of enterEvent

Comments