QGraphicsRectItem设置图像崩溃

问题描述 投票:0回答:1

我正在调查如何将地图图像设置为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)

python pyqt pyqt5 python-3.6 qgraphicsitem
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.