QTooltip的怪异行为应遵循Qgraphictem的鼠标

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

本文关键字:鼠标 Qgraphictem QTooltip      更新时间:2023-10-16

我有一个 QGraphicsView如何显示包含 QGraphicsItemQGraphicsScene。我的项目实现了启动QToolTiphoverMoveEvent(...)方法。

我希望工具提示在鼠标上移到项目上方时跟随鼠标。但是,这只有在我做两件事之一时才有效:

  • 要么创建两个QToolTip S,其中第一个只是一个假人,然后立即被第二个s覆盖。
  • 或第二,将尖端的内容随机制作,例如将rand()放入文本中。

此实施不按应有的作用。它可以让工具提示出现,但不会遵循鼠标。就像它意识到它的内容没有更改,并且不需要任何更新。

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

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

如何通过创建两个工具提示或第二个更新提示的位置而在不进行描述闪烁的情况下完成此工作?

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

请参阅以下内容:如何使qtooltip消息持续?