John Smith
John Smith

Reputation: 11

pyqt get image position

I have an QGraphicsscene on which there is a picture QPixmap into QGraphicsView. I resolved to QPixmap QGraphicsItem.ItemIsMovable. And I want to get the position of the picture when it move. How do I can do this?

Upvotes: 1

Views: 3082

Answers (1)

reclosedev
reclosedev

Reputation: 9522

If you just want to know current image position, you can receive it from pixmapItem.pos() or pixmapItem.x() and pixmapItem.y().

But if you need to know, when it is moved, you can subclass QGraphicsPixmapItem, set QGraphicsItem.ItemSendsGeometryChanges flag, and recieve notification in overrided itemChange function:

#!/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_())

Upvotes: 1

Related Questions