c++qtqpushbuttonqicon

QPushButton not respecting QIcon mode changes


When applying a QIcon with QPushButton::setIcon(), it appears that mode changes don't respect the mode changes set for the QIcon

QIcon helpIcon;
helpIcon.addPixmap(QPixmap(":/icons/style/help.png"), QIcon::Normal);
helpIcon.addPixmap(QPixmap(":/icons/style/help_hover.png"), QIcon::Active); //ignored?

QPushButton *myButton = new QPushButton(this);
myButton->setIcon(helpIcon);

What I would expect to happen is the icon should change from one pixmap to the other when the button is hovered. Instead, the icon stays the same. It only changes when the button is pressed. I've tried every combination of QIcon::State and QIcon::Mode with no change.

Running Qt 5.12.1


Solution

  • I resolved this by subclassing QPushButton and listening for the enter and leave events. This class switches between base and hover icons. This is more useful for me vs stylesheets because I resize the icons based on the user's DPI.

    class CustomButton : public QPushButton
    {
        Q_OBJECT
    public:
        CustomButton(QWidget *parent = nullptr);
    
        void setBaseIcon(QIcon icon){
            baseIcon = icon;
            setIcon(baseIcon);
        }
    
        void setHoverIcon(QIcon icon){hoverIcon = icon;}
    
    private:
        QIcon baseIcon;
        QIcon hoverIcon;
    
    protected:
        virtual void enterEvent(QEvent *){
            setIcon(hoverIcon);
            update();
        }
    
        virtual void leaveEvent(QEvent *){
            setIcon(baseIcon);
            update();
        }
    };