QGraphicsRectItem设置图像崩溃

时间:2018-03-30 15:01:10

标签: python pyqt pyqt5 python-3.6 qgraphicsitem

我正在调查如何将地图图像设置为QGraphicsRectItem对象中的QGraphicsScene对象,我在PyQT5中得到了一个干净的崩溃。

代码是:

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import smopy
from PIL.ImageQt import ImageQt


class MapWidget(QGraphicsRectItem):

    def __init__(self, parent=None):
        super(MapWidget, self).__init__(parent)

        self.setRect(0.0, 0.0, 800, 600)
        self.setFlags(self.ItemIsSelectable | self.ItemIsMovable)
        self.image = None

        # get map
        map = smopy.Map((42., -1., 53., 3.), z=11, tilesize=48)
        img = ImageQt(map.img)
        self.image = QPixmap.fromImage(img)

    def paint(self, painter, option, widget=None):
        painter.drawPixmap(QPoint(0, 0), self.image)


class Window(QDialog):

    def __init__(self):
        super(Window, self).__init__()

        self.layout = QVBoxLayout(self)

        self.view = QGraphicsView()

        self.scene = QGraphicsScene()

        self.view.setScene(self.scene)

        self.layout.addWidget(self.view)

        self.map = MapWidget()

        self.scene.addItem(self.map)

        self.resize(1200, 800)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

输出消息是:

  

处理以退出代码139结束(由信号11中断:   SIGSEGV)

1 个答案:

答案 0 :(得分:1)

可以将其转换为PIL并加载到numpy,而不是将其转换为QImage。另一方面,最好使用QGraphicsPixmapItem,因为它可以正确重新绘制。

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import smopy


class MapWidget(QGraphicsPixmapItem):
    def __init__(self, parent=None):
        super(MapWidget, self).__init__(parent)
        self.setFlags(self.ItemIsSelectable | self.ItemIsMovable)

        # get map
        map = smopy.Map((42., -1., 53., 3.), z=11, tilesize=48)
        numpy_image= map.to_numpy()
        img = QImage(numpy_image.data, *numpy_image.shape[1::-1], QImage.Format_RGB888)
        self.setPixmap(QPixmap.fromImage(img))

class Window(QDialog):
    def __init__(self):
        super(Window, self).__init__()

        self.layout = QVBoxLayout(self)
        self.view = QGraphicsView()
        self.scene = QGraphicsScene()
        self.view.setScene(self.scene)

        self.layout.addWidget(self.view)

        self.map = MapWidget()
        self.scene.addItem(self.map)
        self.resize(1200, 800)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

enter image description here