【问题标题】:Qt : Child graphic items hover eventQt:子图形项目悬停事件
【发布时间】:2013-08-31 19:45:15
【问题描述】:

我有两个 QGraphicsRectItem 类型的项目。一个比一个。

第一个是名为 Wall 的自定义类。墙内有门窗。 事实上,我在这个自定义 Wall 类中有一个门窗列表。

门也是物品,并且画在墙内。

当我将鼠标移到门上时,会发出墙壁的悬停功能,但不会发出门的悬停功能。它们都正确地相互复制了一个,作为受保护的虚拟虚空。

为什么会这样?如何让门窗项目实现悬停?

【问题讨论】:

  • 为什么不定义wall为父类,window和door为wall的子类!?!

标签: qt qt4 hover qgraphicsitem


【解决方案1】:

我尝试使用自定义 QGraphicsItem 而不是自定义 QGraphicsRectItem。似乎为WallDoor 成功调用了悬停事件处理程序。当使用setAcceptHoverEvents(true) 显式设置QGraphicsItem 时会发生这种情况。这未使用自定义 QGraphicsRectItem 进行测试。

#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsItem>
#include <QPainter>

class Item : public QGraphicsItem
{
    QBrush m_brush;
public:
    explicit Item(bool nested = true, QGraphicsItem* parent = 0) : QGraphicsItem(parent), m_brush(Qt::white)
    {
        if (nested) {
            Item* item = new Item(false, this);
            item->setPos(10,10);
            m_brush = Qt::red;
        }
        setAcceptHoverEvents(true);
    }
    QRectF boundingRect() const
    {
        return QRectF(0,0,100,100);
    }
    void hoverEnterEvent(QGraphicsSceneHoverEvent *)
    {
        m_brush = Qt::red;
        update();
    }
    void hoverLeaveEvent(QGraphicsSceneHoverEvent *)
    {
        m_brush = Qt::white;
        update();
    }
    void paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *)
    {
        p->setBrush(m_brush);
        p->drawRoundRect(boundingRect());
    }
};

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QGraphicsScene scene;
    scene.addItem(new Item);
    QGraphicsView view;
    view.setScene(&scene);
    view.setMouseTracking(true);
    view.show();
    return app.exec();
}

【讨论】:

  • 完美!!将标志设置为 true 对我来说是完美的解决方案。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-13
  • 1970-01-01
  • 2015-07-09
  • 2012-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多