qtqt5

How do I tell if a QIcon lacks a valid pixmap?


If I create a QIcon with a pixmap as in the following code snippet:

from PyQt5 import QtGui
icon = QtGui.QIcon(':/images/view-refresh.png')

How do I tell if the icon doesn't have a valid pixmap, e.g. because ':/images/view-refresh.png' wasn't found?


Solution

  • My solution is to wrap the QIcon constructor in a factory function that creates an explicit QPixmap, which is probed to see if it is valid:

    def create_icon(filename):
        pixmap = QtGui.QPixmap(filename)
        if pixmap.isNull():
            raise ValueError('No icon with filename \'{}\' found'.format(filename))
        return QtGui.QIcon(pixmap)
    
    icon = create_icon(':/images/view-refresh.png')
    

    Note that there is also a QIcon.isNull method, but according to the documentation it can be false even if the pixmap is invalid.