1

我有一个 QGraphicsscene,上面有一张图片 QPixmap 到 QGraphicsView。我解决了 QPixmap QGraphicsItem.ItemIsMovable。我想在图片移动时获得图片的位置。我该怎么做?

4

1 回答 1

1

如果您只想知道当前图像位置,您可以从pixmapItem.pos()orpixmapItem.x()和接收它pixmapItem.y()

但是如果您需要知道,当它被移动时,您可以在覆盖函数中继承QGraphicsPixmapItem、设置QGraphicsItem.ItemSendsGeometryChanges标志和接收通知:itemChange

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui


class MovablePixmapItem(QtGui.QGraphicsPixmapItem):
    def __init__(self, pixmap, *args, **kwargs):
        QtGui.QGraphicsPixmapItem.__init__(self, pixmap, *args, **kwargs)
        self.setFlags(QtGui.QGraphicsItem.ItemIsMovable |
                      QtGui.QGraphicsItem.ItemSendsGeometryChanges)

    def itemChange(self, change, value):
        if change == QtGui.QGraphicsItem.ItemPositionHasChanged:
            print value.toPointF()
            # do other work, or emit signal
        return QtGui.QGraphicsPixmapItem.itemChange(self, change, value)


class MainWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.pixmapItem = MovablePixmapItem(QtGui.QPixmap('image.png'))
        self.scene = QtGui.QGraphicsScene()
        self.scene.addItem(self.pixmapItem)
        self.view = QtGui.QGraphicsView(self.scene)
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.view)
        self.setLayout(layout)

    def do_test(self):
        pass


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    widget = MainWidget()
    widget.resize(640, 480)
    widget.show()
    sys.exit(app.exec_())
于 2012-02-24T12:51:07.180 回答