5

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

在此处输入图像描述

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

4

2 回答 2

4

对于这种情况,我将创建一个继承自 QPlainTextEdit 的类,重新实现该event()方法并启用鼠标跟踪setMouseTracking()

明文编辑.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

明文编辑.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);
}

完整代码:这里

于 2017-03-08T18:03:43.840 回答
2

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

cursorForPosition()状态文档

在位置 pos(在视口坐标中)返回一个 QTextCursor。强调添加

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);
}

于 2020-01-10T12:43:01.327 回答