有没有办法在 Qt 中以编程方式中断鼠标拖动?

Is there a way to interrupt a mouse dragging programmatically in Qt?

我想保留用户缩放和拖动 QGraphicsScene 的能力,因此我不能简单地锁定 QGraphicsView。 但是,用户不应该能够将 QGraphicsItem 拖出场景视口。因此,我正在寻找一种在不忽略 DragMoveEvent 的情况下中断 MouseDragEvent 的方法(也就是让 QGraphicsItem 跳回到其原点)。我曾尝试使用 releaseMouse() 函数来完成此行为,但那根本不起作用。有什么建议吗?

谢谢!

在处理qt图形场景视图框架工作和拖动时,re-implementQGraphicsItemand::itemChange比直接用鼠标处理好

这是头文件中定义的函数:

protected:
virtual QVariant itemChange( GraphicsItemChange change, const QVariant & value );

然后在函数中,检测位置变化,并根据需要 return 新位置。

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;
    }

   ...
}

像这样,你懂的。