Adding QPixmap element to QGraphicsScene using QGraphicsScene :: addItem PySide crashes

I am trying to add an image to QGraphicsView / QGraphicsScene , so later I can draw simple geometries on it based on user input. I need to make sure the image conforms to QGraphicsView regardless of its format. And for this I use QGraphicsView::fitInView

Working version:

I can add, display and set the image successfully if I use QGraphicsScene::addPixmap

 from PySide import QtGui import sys app = QtGui.QApplication(sys.argv) scn = QtGui.QGraphicsScene() view = QtGui.QGraphicsView(scn) pixmap = QtGui.QPixmap("image.png") gfxPixItem = scn.addPixmap(pixmap) view.fitInView(gfxPixItem) view.show() sys.exit(app.exec_()) 

Non-working version:

However, if instead of using QGraphicsScene::addPixmap , I first create a QGraphicsPixmapItem and add it to the scene using QGraphicsScene::addItem , I get a segfault !

 from PySide import QtGui import sys app = QtGui.QApplication(sys.argv) scn = QtGui.QGraphicsScene() view = QtGui.QGraphicsView(scn) pixmap = QtGui.QPixmap("image.png") pixItem = QtGui.QGraphicsPixmapItem(pixmap) gfxPixItem = scn.addItem(pixItem) view.fitInView(gfxPixItem) # Crashes, see below for call stack in OSX view.show() sys.exit(app.exec_()) 

I tried this on OSX as well as on Linux with the same result. What am I doing wrong here?

The reason I need a second approach is because I can subclass QGraphicsPixmapItem override mouseEvent functions.


This is the thread that crashes:

 0 QtGui 0x000000011073bb52 QGraphicsItem::isClipped() const + 4 1 QtGui 0x0000000110779ad6 QGraphicsView::fitInView(QGraphicsItem const*, Qt::AspectRatioMode) + 32 2 QtGui.so 0x000000010f72333d Sbk_QGraphicsViewFunc_fitInView + 1153 3 org.python.python 0x000000010f2895a9 PyEval_EvalFrameEx + 9244 4 org.python.python 0x000000010f287147 PyEval_EvalCodeEx + 1934 5 org.python.python 0x000000010f2869b3 PyEval_EvalCode + 54 6 org.python.python 0x000000010f2c2c70 0x10f270000 + 339056 7 org.python.python 0x000000010f2c2d3c PyRun_FileExFlags + 165 8 org.python.python 0x000000010f2c2726 PyRun_SimpleFileExFlags + 410 9 org.python.python 0x000000010f2e6e27 Py_Main + 2715 10 libdyld.dylib 0x00007fff861b47e1 start + 1 
+4
source share
1 answer

QGraphicsScene::addItem(QGraphicsItem *item) returns void , so gfxPixItem is None. When you try to call view.fitInView(None) , it crashes.

Corrected Code:

 pixmap = QtGui.QPixmap("image.png") pixItem = QtGui.QGraphicsPixmapItem(pixmap) scn.addItem(pixItem) view.fitInView(pixItem) 
+3
source

Source: https://habr.com/ru/post/1485162/


All Articles