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

时间:2017-02-14 00:13:20

标签: c++ qt drag-and-drop qgraphicsscene

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

谢谢!

1 个答案:

答案 0 :(得分:1)

在处理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;
    }

   ...
}

像这样,你明白了。

相关问题