如何在 QPlainTextEdit 中为突出显示的字符串创建工具提示

how to create tooltip for highlighted strings in QPlainTextEdit

我有一个 QPlainTextEdit 并且其中突出显示了一些单词,现在我想要当我将鼠标悬停在它上面时,它会显示一个工具提示,其中包含关于这个突出显示的单词的描述或类似的东西 QT IDE

但我不知道如何开始这个所以任何想法、代码或类似的项目都可以检查这个。

对于这种情况,我将创建一个继承自 QPlainTextEdit 的 class,重新实现 event() 方法并使用 setMouseTracking()

启用鼠标跟踪

plaintextedit.h

#ifndef PLAINTEXTEDIT_H
#define PLAINTEXTEDIT_H

#include <QPlainTextEdit>

class PlainTextEdit : public QPlainTextEdit
{
public:
    PlainTextEdit(QWidget *parent=0);

    bool event(QEvent *event);
};

#endif // PLAINTEXTEDIT_H

plaintextedit.cpp

#include "plaintextedit.h"
#include <QToolTip>


PlainTextEdit::PlainTextEdit(QWidget *parent):QPlainTextEdit(parent)
{
    setMouseTracking(true);
}

bool PlainTextEdit::event(QEvent *event)
{
    if (event->type() == QEvent::ToolTip)
    {
        QHelpEvent* helpEvent = static_cast<QHelpEvent*>(event);
        QTextCursor cursor = cursorForPosition(helpEvent->pos());
        cursor.select(QTextCursor::WordUnderCursor);
        if (!cursor.selectedText().isEmpty())
            QToolTip::showText(helpEvent->globalPos(), /*your text*/QString("%1 %2").arg(cursor.selectedText()).arg(cursor.selectedText().length()) );

        else
            QToolTip::hideText();
        return true;
    }
    return QPlainTextEdit::event(event);
}

完整代码:Here

@eyllanesc 的回答很好,但我想补充一点,如果您设置了视口边距,则必须调整位置,否则会发生偏移,并报告错误的光标位置。

cursorForPosition() 的文档指出

returns a QTextCursor at position pos (in viewport coordinates). emphasis added

bool PlainTextEdit::event(QEvent *event)
{
    if (event->type() == QEvent::ToolTip)
    {
        QHelpEvent* helpEvent = static_cast<QHelpEvent*>(event);
        
        QPoint pos = helpEvent->pos();
        pos.setX(pos.x() - viewportMargins().left());
        pos.setY(pos.y() - viewportMargins().top());
        
        QTextCursor cursor = cursorForPosition(pos);
        cursor.select(QTextCursor::WordUnderCursor);
        if (!cursor.selectedText().isEmpty())
            QToolTip::showText(helpEvent->globalPos(), /*your text*/QString("%1 %2").arg(cursor.selectedText()).arg(cursor.selectedText().length()) );

        else
            QToolTip::hideText();
        return true;
    }
    return QPlainTextEdit::event(event);
}