2
votes

I have a QGraphicsView. To that I added a QGraphicsScene and to that a added an QPixmap(*.jpeg) and QGraphicsEllipseItem(a circle). The QPixmap is much more bigger than the QGraphicsView, so scrolling is enabled. The problem is that both QPixmap and QGraphicsEllipseItem are moving. But I want a fixed position for the QGraphicsEllipseItem in QGraphicsView. It should always be in the center of the QGraphicsView. How can I do that? Hope someone can help.

2

2 Answers

1
votes

Add a signal handler for the scroll signal of the scroll bars (use QAbstractSlider::sliderMoved()).

Then you can query the view for it's left/top offset and size and position the circle accordingly. See the explanation for QAbstractScrollArea to get you started.

1
votes

If you subclass QGraphicsView, you can override the scrollContentsBy method to set the position of the ellipse whenever the scroll area changes. Here's some really minimal code:

import sys
from PyQt4 import QtGui

class MyView(QtGui.QGraphicsView):
    def __init__(self, scene, parent = None):
        super(MyView, self).__init__(parent)
        self.scene = scene
        self.setScene(scene)
        self.ellipse = QtGui.QGraphicsEllipseItem(0, 0, 30, 30, scene = self.scene)
        self.scene.addItem(self.ellipse)

    def scrollContentsBy(self, x, y):
        super(MyView, self).scrollContentsBy(x, y)
        self.ellipse.setPos(self.mapToScene(28, 28))

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent = None):
        super(MainWindow, self).__init__(parent)
        pixmap = QtGui.QPixmap()
        pixmap.load('imagefile.jpg')
        scene = QtGui.QGraphicsScene(self)
        scene.setSceneRect(0, 0, pixmap.width(), pixmap.height())
        item = QtGui.QGraphicsPixmapItem(pixmap)
        scene.addItem(item)
        self.view = MyView(scene, self)
        self.view.setMinimumSize(100, 100)

def main():
    app = QtGui.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    app.exec_()

if __name__ == '__main__':
    main()