开发者

Pyqt: How-to set item always in the center of a QGraphicsView when scrolling is possible?

开发者 https://www.devze.com 2023-01-14 05:06 出处:网络
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 muc开发者_开发知识库h more bigger than the QGraphicsV

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 muc开发者_开发知识库h 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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号