Frage

I have two items of type QGraphicsRectItem. One over the other.

The first one is a custom class called Wall. Inside the wall there are windows and doors. In fact, i have a list of Doors and Windows inside this custom Wall class.

The Doors are Items too, and are drawn inside the wall.

When i move the mouse over the door, the hover function of the wall is emited, but the hover of the door is not. Both of them correctly copied one from each other as virtual void protected.

Why is that happening? How can i make the door and window items realize about the hover?.

War es hilfreich?

Lösung

I have tried with a custom QGraphicsItem instead of a custom QGraphicsRectItem. It seems the hover event handler is successfully called for both Wall and Door. This is happening when explicitly setting QGraphicsItem with setAcceptHoverEvents(true). This is not tested with custom QGraphicsRectItem.

Screenshot

#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();
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top