如何将 QGraphicsView 翻译到我双击的位置?

How do I translate the QGraphicView to the position where I doulbleclicked?

我正在尝试将 QGraphicView 的位置转换为我双击的位置。我尝试了 translatecenterOn 函数,但其​​中 none 有效。所以我 gessing 我做错了什么。

举个简单的例子,如果我使用这段代码:

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys



class SurfViewer(QMainWindow):
    def __init__(self, parent=None):
        super(SurfViewer, self).__init__()
        self.parent = parent
        self.setFixedWidth(600)
        self.setFixedHeight(600)
        photo = PhotoViewer()
        self.setCentralWidget(photo)


class PhotoViewer(QGraphicsView):
    def __init__(self, parent=None):
        super(PhotoViewer, self).__init__(parent)
        self.parent=parent
        self.scene = QGraphicsScene(self)
        self.setScene(self.scene)
        self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setFrameShape(QFrame.NoFrame)
        self.UpdateScene()
        self.scene.update()

    def mouseDoubleClickEvent(self, event):
        position = QPointF(event.pos())
        position = self.mapToScene(position.x(),position.y())
        print(position)
        print(position.isNull())
        if not position.isNull():
            #self.centerOn(position)
            print(position.x(),position.y())
            self.centerOn(position.x(),position.y())
            self.scene.update()
            self.update()

    def UpdateScene(self,):
        xsize=100
        ysize=100
        newitem = QGraphicsEllipseItem(0-xsize/2., 0-ysize/2., xsize, ysize)
        newitem.setBrush(QBrush(Qt.black, style = Qt.SolidPattern))
        self.scene.addItem(newitem)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = SurfViewer(app)
    ex.setWindowTitle('window')
    ex.show()
    sys.exit(app.exec_( ))

我在视图中间绘制了一个圆圈。当我双击视图时,我进入 mouseDoubleClickEvent 功能,并在单击 QPointF(event.pos()) 期间获得鼠标的坐标。希望这是有效的。

现在我希望我得到的位置是视图的中心。所以我尝试用 translatecenterOn 翻译视图,但没有任何反应。我也尝试将坐标映射到场景,但这也无济于事。

centerOn() only makes the position visible, if it is already visible it will not make any change. The solution is to move the sceneRect 以按下的点为中心:

def mouseDoubleClickEvent(self, event):
    p = self.mapToScene(event.pos())
    r = self.sceneRect()
    r.moveCenter(p)
    self.setSceneRect(r)