pyqtpysideqpalette

How to get groups and roles of a QPalette in PyQt/PySide?


Instead of "manually" defining lists groups and roles (in my code below), how can I query the PyQt/PySide application for these values?

from PyQt4 import QtGui

groups = ['Disabled', 'Active', 'Inactive', 'Normal']
roles = [
            'AlternateBase',
            'Background', 
            'Base',
            'Button',
            'ButtonText',
            'BrightText',
            'Dark',
            'Foreground',
            'Highlight',
            'HighlightedText',
            'Light',
            'Link',
            'LinkVisited',
            'Mid',
            'Midlight',
            'Shadow',
            'ToolTipBase',
            'ToolTipText',
            'Text',
            'Window',
            'WindowText'
        ]

def getPaletteInfo():
    palette = QtGui.QApplication.palette()
    #build a dict with all the colors
    result = {}    
    for role in roles:
        print role
        for group in groups:
            qGrp = getattr(QtGui.QPalette, group)
            qRl = getattr(QtGui.QPalette, role)
            result['%s:%s' % (role, group)] =  palette.color(qGrp, qRl).rgba()
    return result

Solution

  • This can be done with standard python introspection techniques:

    for name in dir(QtGui.QPalette):
        if isinstance(getattr(QtGui.QPalette, name), QtGui.QPalette.ColorGroup):
            print(name)
    

    and the same can be done with QtGui.QPalette.ColorRole.

    But note that this will produce a few extra items that you might not be expecting. There are NColorGroups and NColorRoles. which give the number of items in each enum; there are a few synonyms, such as Window/Background; and one or two others, such as All and NoRole.