QTextEdit:获取鼠标指针下的单词

QTextEdit: get word under the mouse pointer

我做了这个 CompileOutput class,基本上我想要的是当我点击单词时,它会发出信号 selectedWord,当我将鼠标悬停在单词上时,我想要它发射信号 hoveredWord.

mousePressEvent 有效,但 enterEvent 无效。当我将鼠标悬停在文字上时,没有任何反应。

这是我的代码块:

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
    }

}

试试这个:

在构造函数中添加

setMouseTracking(true);

然后使用 mouseMoveEvent 而不是 enterEvent