Search code examples
user-interfaceqtqt4

Set a custom icon for a QAction when disabled


Is it possible to have a custom icon displayed for a QAction when it is disabled? E.g. display icon A when the tool is enabled and icon B when the tool is disabled.


Solution

  • When creating a QAction, you pass it a QIcon. Although I haven't tried this myself, I've noticed that QIcon has a function void QIcon::addPixmap ( const QPixmap & pixmap, Mode mode = Normal, State state = Off ). The Mode can be one of Normal, Disabled, Active, or Selected. Thus, I presume something like this would work:

    QPixmap enabled_icon( "enabled.png" );
    QPixmap disabled_icon( "disabled.png" );
    QIcon icon( enabled_icon );
    icon.addPixmap( disabled_icon, QIcon::Disabled );
    QAction action( icon, "&Menu action..." );
    

    I would be interested in learning if this actually does work. I've never gotten around to testing it, but it seems like exactly the use this was designed for.