我在QGraphicsScene上有三个项目,比如" 1"," 2"和" 3"。 " 3"是" 2"的孩子。 setAcceptHoverEvents在所有这些上启用。
问题是当我将项目悬停在" 3" item" 2"即使鼠标位置位于2的边界内,也会被标记。如何独立悬停子项?
#include "GraphicsView.h"
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QGraphicsSceneHoverEvent>
class GraphicsRectItem: public QGraphicsRectItem
{
public:
GraphicsRectItem(qreal x, qreal y, qreal w, qreal h, const QString& label,
QGraphicsItem* parent = nullptr)
: QGraphicsRectItem(x, y, w, h, parent)
, m_label(new QGraphicsSimpleTextItem(label, this))
{
setBrush(Qt::white);
setAcceptHoverEvents(true);
}
protected:
void hoverEnterEvent(QGraphicsSceneHoverEvent* event)
{
setBrush(Qt::lightGray);
QGraphicsItem::hoverEnterEvent(event);
}
void hoverLeaveEvent(QGraphicsSceneHoverEvent* event)
{
setBrush(Qt::white);
QGraphicsItem::hoverLeaveEvent(event);
}
protected:
QGraphicsSimpleTextItem* m_label;
};
GraphicsView::GraphicsView(QWidget* parent)
: QGraphicsView(parent)
, m_scene(new QGraphicsScene(this))
, m_rect1(new GraphicsRectItem(0, 0, 100, 100, " 1"))
, m_rect2(new GraphicsRectItem(0, 0, 100, 100, " 2"))
, m_rect3(new GraphicsRectItem(0, 0, 100, 100, " 3", m_rect2))
{
m_scene->addItem(m_rect1);
m_scene->addItem(m_rect2);
m_rect2->setPos(40, 40);
m_rect3->setPos(40, 40);
setScene(m_scene);
}
GraphicsView::~GraphicsView()
{}