1

I'm trying to translate the position of the QGraphicView to the position where I doubleclicked on. I tried the function translate and centerOn but none of them work. So I'm gessing I'm doing something wrong.

For a simple example, if I use this code:

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_( ))

I plot a circle in the middle of the view. when I double click on the view, I enter to the mouseDoubleClickEvent fonction and I get the coordinate of the mouse during the click with QPointF(event.pos()). Hopefully, this is working.

Now I would like the position I got be the center of the view. So I tried to translate the view with both translate or centerOn but nothing happend. I also try to map the corrdinate to the scene but that didn't help neither.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
ymmx
  • 4,769
  • 5
  • 32
  • 64

1 Answers1

2

centerOn() only makes the position visible, if it is already visible it will not make any change. The solution is to move the sceneRect centering it on the point that is pressed:

def mouseDoubleClickEvent(self, event):
    p = self.mapToScene(event.pos())
    r = self.sceneRect()
    r.moveCenter(p)
    self.setSceneRect(r)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241