以编程方式滚动QGraphicsView

时间:2009-07-09 14:39:07

标签: python qt

我想在我的(Py)Qt应用程序中的QGraphicsView上实现滚动/平移功能。它应该像这样工作:用户按下鼠标中键,当用户移动鼠标时视图会滚动(这是一个非常常见的功能)。
我尝试使用从QWidget继承的scroll()方法。但是,这会以某种方式移动视图 - 滚动条和所有。见图。
所以,鉴于这不是我应该这样做的方式,我该怎么办?或者这是正确的方法,但我做错了什么?我使用的代码:

   def __init__(self):
       ...

       self.ui.imageArea.mousePressEvent=self.evImagePress
       self.ui.imageArea.mouseMoveEvent=self.evMouseMove

       self.scrollOnMove=False
       self.scrollOrigin=[]

       ...

   def evImagePress(self, event):
        if event.button() == Qt.LeftButton:
            self.evImageLeftClick(event)
        if event.button() == Qt.MidButton:
            self.scrollOnMove=not self.scrollOnMove
            if self.scrollOnMove:
                self.scrollOrigin=[event.x(), event.y()]
   ...

   def evMouseMove(self, event):
        if self.scrollOnMove:
            self.ui.imageArea.scroll(event.x()-self.scrollOrigin[0],
                                     event.y()-self.scrollOrigin[1])

除了整个移动小部件业务外,它的工作正如我所料。

Fails to scroll http://img55.imageshack.us/img55/3222/scrollfail.jpg

4 个答案:

答案 0 :(得分:4)

我对translate()方法的补充。 除非你缩放场景,否则效果很好。如果这样做,您会注意到图像与鼠标移动不同步。这就是mapToScene()来帮助的时候。您应该将点从鼠标事件映射到场景坐标。然后映射的差异转换为translate(),瞧中提琴 - 你的场景跟随你的鼠标非常精确。

例如:

QPointF tmp2 = mapToScene(event->pos());
QPointF tmp = tmp2.mapToScene(previous_point);
translate(tmp.x(),tmp.y());

答案 1 :(得分:3)

我自己没有这样做,但这来自QGraphicsView文档

  

......当场景较大时   比滚动条的值,你可以   选择使用translate()进行导航   而是场景。

使用scroll移动小部件,translate应该可以实现您的目标,移动视图下方QGraphicsScene的内容

答案 2 :(得分:1)

丹尼斯给出的答案是正确的,以便翻译工作。 PF4Public的评论也是有效的:这可能会导致缩放。我的解决方法与P4FPublc不同 - 而不是mapToScene我保留锚并在翻译后恢复它:

previousAnchor = view.transformationAnchor()
#have to set this for self.translate() to work.
view.setTransformationAnchor(QGraphicsView.NoAnchor)
view.translate(x_diff,y_diff)
#have to reset the anchor or scaling (zoom) stops working:
view.setTransformationAnchor(previousAnchor)

答案 3 :(得分:0)

您可以使用方法QGraphicsView::setSceneRect()设置QGraphicsView将显示的QGraphicsScene区域。因此,当您按下按钮并移动鼠标时,您可以更改场景显示部分的中心并实现目标。