setPixmap crashing when trying to show image in label

一笑奈何 提交于 2020-12-21 04:05:26

问题


I have created a minimal example with pyqt designer, that changes the text of a label when a button is pressed and is supposed to present a screenshot in the window, via the label.

Unfortunately, the example just crashes when it tries to show the screenshot in the label.

from PIL.ImageQt import ImageQt
from PyQt5 import QtCore, QtGui, QtWidgets
from pyscreenshot import grab

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(503, 382)
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(70, 30, 75, 23))
        self.pushButton.setObjectName("pushButton")
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(80, 100, 47, 14))
        self.label.setObjectName("label")

        self.retranslateUi(Form)
        self.pushButton.clicked.connect(lambda: self.take_screenshot())
        QtCore.QMetaObject.connectSlotsByName(Form)

    def take_screenshot(self):
        self.label.setText("1?")
        screenshot = grab()
        self.label.setText("2")
        qim = ImageQt(screenshot)
        pix = QtGui.QPixmap.fromImage(qim)
        self.label.setText("3")
        self.label.setPixmap(pix)



    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton.setText(_translate("Form", "PushButton"))
        self.label.setText(_translate("Form", "TextLabel"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

回答1:


"screenshot" shares the same memory with "qimg", and as screenshot it is a local variable that when eliminated the associated memory is also eliminated so the QPbelmap of the QLabel when trying to access information will generate a Segmentation fault. The solution is to make a copy so that they do not share the same memory

def take_screenshot(self):
    screenshot = grab()
    qim = ImageQt(screenshot).copy()
    pix = QtGui.QPixmap.fromImage(qim)
    self.label.setPixmap(pix)
    self.label.adjustSize()


来源:https://stackoverflow.com/questions/61354609/setpixmap-crashing-when-trying-to-show-image-in-label

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!