当 QToolTip 应该跟随 QGraphicsItem 上的鼠标时出现奇怪的行为

Weird behaviour of QToolTip when it should follow the mouse who is over a QGraphicsItem

我有一个 QGraphicsView 如何显示一个 QGraphicsScene 其中包含一个 QGraphicsItem。我的项目实现了 hoverMoveEvent(...) 方法,该方法触发了 QToolTip.

我希望工具提示在鼠标移动到项目上方时跟随鼠标。但是,这仅在我执行以下两项操作之一时才有效:

此实现无法正常工作。它让工具提示出现,但它不跟随鼠标。就好像它意识到它的内容没有改变,不需要任何更新一样。

void MyCustomItem::hoverMoveEvent(QGraphicsSceneHoverEvent *mouseEvent)
{
    QToolTip::showText(mouseEvent->screenPos(), "Tooltip that follows the mouse");
}

此代码创建了所需的结果。工具提示跟随鼠标。缺点是,由于创建了两个工具提示,您会看到轻微的闪烁。

 void MyCustomItem::hoverMoveEvent(QGraphicsSceneHoverEvent *mouseEvent)
    {
QToolTip::showText(mouseEvent->screenPos(), "This is not really shown and is just here to make the second tooltip follow the mouse.");
        QToolTip::showText(mouseEvent->screenPos(), "Tooltip that follows the mouse");
    }

第三,提出的解决方案 here 也有效。但是我不想显示坐标。工具提示的内容是静态的...

如何通过创建两个工具提示或第二次更新提示的位置来完成这项工作而不会出现所描述的闪烁?

QTooltip 被创建为在您移动鼠标后立即消失,要没有这种行为,您可以使用 QLabel 并启用 Qt::ToolTip 标志。你的情况:

.h

private:
    QLabel *label;

.cpp

MyCustomItem::MyCustomItem(QGraphicsItem * parent):QGraphicsItem(parent)
{
    label = new QLabel;
    label->setWindowFlag(Qt::ToolTip);
    [...]
}

在您想显示消息的位置之后,如果您想在 hoverMoveEvent 中显示消息,您应该放置以下代码。

label->move(event->screenPos());
label->setText("Tooltip that follows the mouse");
if(label->isHidden())
    label->show();

要隐藏它,您必须使用:

label->hide();

看到这个: