neziy neziy - 7 months ago 19
Python Question

-SOLVED-How to place an image at a certain position in QtGraphicsView/QtGraphicsScene (PyQt4)?

I'm creating an application using Qt Designer and PyQt4. I want to know how I can add an image to the

QtGraphicsView
widget to my desired location.
For example, when I click on the
QtGraphicsView
widget, I want to add an image to that exact location. I've searched online but I couldn't find anything that was of any help.

I've created a scene subclass to manage the items that will be displayed in the
QtGraphicsView
widget. I'm able to get the coordinates of the place where I click but I don't know how to place the item in that certain position. Below is my code:

class graphicsScene(QtGui.QGraphicsScene):
def __init__(self, parent=None):
super(graphicsScene, self).__init__(parent)

def mousePressEvent(self, event):
position = QtCore.QPointF(event.scenePos())
pixmap = QtGui.QPixmap("host.png")
pixmap_scaled = pixmap.scaled(30, 30, QtCore.Qt.KeepAspectRatio)
self.itemAt(pixmap_scaled,position.x(),position.y())

self.addPixmap(pixmap_scaled)
print "pressed here: " + str(position.x()) + ", " + str(position.y())
self.update()


def mouseReleaseEvent(self, event):
position = QtCore.QPointF(event.scenePos())
print "released here: " + str(position.x()) + ", " + str(position.y())
self.update()

class form(QtGui.QMainWindow):
def __init__(self):
super(mininetGUI, self).__init__()
self.ui = uic.loadUi('form.ui')

self.scene = graphicsScene()
self.ui.view.setScene(self.scene)

Answer

Use addItem(your_pixmap_object) to add the QPixmap to the scene. Then you can use setPos(...) on the returned QGraphicsItem (this is returned when you use addItem(...) and the insertion of the item into the scene was succcessful).The point that you pass to your setPos(...) would be the one that is part of the event (as you have done already by calling event.scenePos()).

pixmap = QPixmap(...)
sceneItem = self.addItem(pixmap)
sceneItem.setPos(event.scenePos())

If you want to use QGraphicsPixmapItem the procedure is the same as the one above but just use self.addPixmap(...) as you have done in your code.

There is one thing that you might want to handle in addition to just placing the item - the case where you press the mouse button, move the cursor somewhere else in the scene while still pressing the button and then release it. This will insert the item at the starting position of your movement event (while pressing the button and moving) however this might not be what you want to do. You have to think about whether it will be better to handle the insertion inside the mouseReleaseEvent(...) instead. It really depends on how you want things to work for this particular scenario.