Search code examples
pythonpyqt4qpixmap

How do I add StandardPixmap to a layout?


I am trying to get the built in StandardPixmaps to display on my layout.

So far I have managed to access a standard pixmap (PyQt4.QtGui.QStyle.SP_MessageBoxWarning), but seem unable to actually add this to my layout. I have tried adding it to a QLabel using the setPixmap method, but this requires a pixmap, not a standardPixmap.

I have found this answer on SO, which led me to the standardPixmaps, but I have been unable to make any more progress from here.


Solution

  • PyQt4.QtGui.QStyle.SP_MessageBoxWarning is an enumeration value not a pixmap.

    In order to get a pixmap from it, you could give it to the standardPixmap method of the current used style.

    Example:

    from PyQt4 import QtGui
    
    if __name__ == '__main__':
        app = QtGui.QApplication([])
        label = QtGui.QLabel()
        label.setPixmap(app.style().standardPixmap(QtGui.QStyle.SP_MessageBoxWarning))
        label.show()
        app.exec_()
    

    Unfortunately, the standardPixmap method is considered obsolete now. The Qt doc advises to use the standardIcon method which returns a QIcon.

    If you still want to use a QLabel to display your icon, you have to build a QPixmap from the QIcon you get. You can use one of its pixmap methods for this:

    from PyQt4 import QtGui
    
    if __name__ == '__main__':
        app = QtGui.QApplication([])
        label = QtGui.QLabel()
        icon =  app.style().standardIcon(QtGui.QStyle.SP_MessageBoxWarning)
        label.setPixmap(icon.pixmap(32))
        label.show()
        app.exec_()