我有QGraphicsView
一个更大QGraphicsScene
的可以拖动的。在QGraphicsScene
我有一个显示 a的子类QGraphicsItem
( ) ,它可以有随机的形状。(我不直接使用,因为将来要实现额外的功能)TestItem
QGraphicsPixmapItem
QGraphicsPixmapItem
我希望这个项目是可移动的,但前提是用户在项目的形状内按下。如果在形状之外,但仍在 内部boundingRectangle
,我希望拖动它后面的场景。这是因为它boundingRectangle
可以比形状大得多并且用户看不到它,所以尝试将场景拖到附近Pixmap
并且它不起作用会很奇怪。
这是我的子类项目:
TestItem::TestItem(QPointF position, QPixmap testImage, double width,
double length, QGraphicsItem * parent):
QGraphicsItem(parent),
m_boundingRect(QRectF(0,0,5, 5)),
m_dragValid(false),
m_path(QPainterPath()),
mp_image(new QGraphicsPixmapItem(this))
{
setBoundingRect(QRectF(0,0,width,length));
setPos(position - boundingRect().center());
setFlag(QGraphicsItem::ItemIsMovable);
mp_image->setPixmap(testImage.scaled(width, length));
m_path = mp_image->shape();
}
QPainterPath TestItem::shape()
{
return m_path;
}
QRectF TestItem::boundingRect() const
{
return m_boundingRect;
}
void TestItem::setBoundingRect(QRectF newRect)
{
prepareGeometryChange();
m_boundingRect = newRect;
}
我试过像这样覆盖鼠标事件,但它给我带来的只是在形状之外但在边界矩形内时根本没有功能
void TestItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if(shape().contains(event->pos()))
{
QGraphicsItem::mousePressEvent(event);
m_dragValid = true;
}
}
void TestItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if(m_dragValid)
QGraphicsItem::mouseMoveEvent(event);
}
void TestItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
if(m_dragValid)
QGraphicsItem::mouseReleaseEvent(event);
m_dragValid = false;
}
这当然是有道理的,但我不知道如何实现场景的拖动,因为将鼠标事件发送到图形项的是场景本身。
(我QGraphicsView
的设置为DragMode
QGraphicsView::ScrollHandDrag
)
有人有想法吗?