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

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

本文关键字:方式 编程 中断 鼠标 拖动 Qt 有没有      更新时间:2023-10-16

我想保留用户缩放和拖动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;
    }
   ...
}

像这样的东西,你明白了。