我想保留用户缩放和拖动QGraphicsScene
的能力,因此我不能简单地锁定QGraphicsView
。但是,用户不应能够将QGraphicsItem
拖出场景视口。因此,我正在寻找一种方法来中断MouseDragEvent而不忽略DragMoveEvent(也就是QGraphicsItem
跳回到其原点(。我试图使用 releaseMouse()
-函数完成此行为,但这根本不起作用。有什么建议吗?
谢谢!
在处理 qt 图形场景视图框架工作和拖动时,最好重新实现 QGraphicsItemand::itemChange,而不是直接处理鼠标。
这是头文件中定义的函数:
protected:
virtual QVariant itemChange( GraphicsItemChange change, const QVariant & value );
然后在函数中,检测位置变化,并根据需要返回新位置。
QVariant YourItemItem::itemChange(GraphicsItemChange change, const QVariant & value )
{
if ( change == ItemPositionChange && scene() )
{
QPointF newPos = value.toPointF(); // check if this position is out bound
{
if ( newPos.x() < xmin) newPos.setX(xmin);
if ( newPos.x() > xmax ) newPos.setX(xmax);
if ( newPos.y() < ymin ) newPos.setY(ymin);
if ( newPos.y() > ymax ) newPos.setY(ymax);
return newPos;
}
...
}
像这样的东西,你明白了。