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

标签 c++ qt qt5 qgraphicsitem qtooltip

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

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

  • 要么创建两个 QToolTip,其中第一个只是一个虚拟对象并立即被第二个覆盖。
  • 或者其次,使提示的内容随机,例如将 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");
    }

三、给出的解决方案here也有效。但是我不想显示坐标。 tooltip的内容是静态的...

如何通过创建两个工具提示或第二次更新提示的位置来使这项工作没有所描述的闪烁?

最佳答案

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

看到这个:How to make QToolTip message persistent?

关于c++ - 当 QToolTip 应该跟随 QGraphicsItem 上的鼠标时出现奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44736503/

相关文章:

c++ - 如何在类定义中声明基本截止时间计时器

c++ - 非静态数据成员类推导

c++ - CMakeList 设置 CMAKE_PREFIX_PATH

python - 如何在 PyQt5 (5.13) 中启用 macOS 深色模式

c++ - 如何*正确*地将 std::string 转换为无符号 char[] 数组。我想我做错了,有人指出我正确的方向吗?

c++ - 如何获取大小c++动态数组

qt - 为按钮控件 Qt Widgets 样式表定义多种样式

c++ - QVideoWidget 不能很好地调整大小

Qt5 MinGW 未定义对 ConvertStringToBSTR 的引用

c++ - 如何为 linux 机器创建 Qt 可执行文件