为什么 PyQt5 QPixmap 会导致 python 崩溃?

2022-01-12 00:00:00 python pyqt5 crash qpixmap

问题描述

当我尝试将此字符串列表转换为像素图时,python 会崩溃.有什么建议可以解决这个问题?

When I try and convert this list of strings to a pixmap it crashes python. Any suggestions to pix this?

openIcon = [
    '16 13 5 1',
    '. c #040404',
    '# c #808304',
    'a c None',
    'b c #f3f704',
    'c c #f3f7f3',
    'aaaaaaaaa...aaaa',
    'aaaaaaaa.aaa.a.a',
    'aaaaaaaaaaaaa..a',
    'a...aaaaaaaa...a',
    '.bcb.......aaaaa',
    '.cbcbcbcbc.aaaaa',
    '.bcbcbcbcb.aaaaa',
    '.cbcb...........',
    '.bcb.#########.a',
    '.cb.#########.aa',
    '.b.#########.aaa',
    '..#########.aaaa',
    '...........aaaaa'
    ]

if __name__ == "__main__":
    from PyQt5.QtGui import QPixmap
    openIcon_p = QPixmap(openIcon)
    openIcon_p.save("openIcon.png")

使用:

Win32 上的 Python 3.7.4(tags/v3.7.4:e09359112e,2019 年 7 月 8 日,20:34:20)[MSC v.1916 64 位 (AMD64)]

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32

PyQt5==5.13.0

PyQt5==5.13.0


解决方案

从控制台运行代码以查看错误消息.你需要一个 QApplicationQPixmap 之前:

run the code from console to see the error messages. You need a QApplication before QPixmap:

from PyQt5 import QtWidgets, QtGui
import sys

openIcon = [
    '16 13 5 1',
    '. c #040404',
    '# c #808304',
    'a c None',
    'b c #f3f704',
    'c c #f3f7f3',
    'aaaaaaaaa...aaaa',
    'aaaaaaaa.aaa.a.a',
    'aaaaaaaaaaaaa..a',
    'a...aaaaaaaa...a',
    '.bcb.......aaaaa',
    '.cbcbcbcbc.aaaaa',
    '.bcbcbcbcb.aaaaa',
    '.cbcb...........',
    '.bcb.#########.a',
    '.cb.#########.aa',
    '.b.#########.aaa',
    '..#########.aaaa',
    '...........aaaaa'
    ]

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv) 
    openIcon_p = QtGui.QPixmap(openIcon)
    openIcon_p.save("openIcon.png")

如果没有添加的行,代码会给出以下错误消息:

without the added line the code gives the following error message:

QPixmap::fromImageInPlace: QPixmap cannot be created without a QGuiApplication
QPixmap: Must construct a QGuiApplication before a QPixmap 

有关说明,请参阅 Qt-Documentation.还有一个描述何时使用 QtWidgets.QApplication 以及何时使用 eyllanesc 评论的 QtGui.QGuiApplication

for explanation see Qt-Documentation. there is also a description when to use QtWidgets.QApplication and when QtGui.QGuiApplication as commented by eyllanesc

相关文章