Search code examples
pythoncrashpyqt5qpixmap

Why does PyQt5 QPixmap crash 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")

Using:

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


Solution

  • 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")
    

    Edit: 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 
    

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