Important: Please read the Qt Code of Conduct -

QPushButton checkable only by code

  • I have this required scenario:

    • QPushButton that reacts to clicks
    • at run-time, based on some criteria I will set its checked state to true or false

    I mean, when the user clicks on the button it should just fire the clicked signal without change it's checked state. But at the same time I need to change its checked state programmatically whenever is needed.

    Any idea about?

  • Solved subclassing QPushButton and by-passing the isCheckable constraint.

  • @Mark81 if your issue is solved, please don't forget to mark the post as such! Thanks.

  • Here a very quick and dirty solution:

    #ifndef CHECKBUTTON_H
    #define CHECKBUTTON_H
    #include <QObject>
    #include <QPushButton>
    class CheckButton : public QPushButton
        explicit CheckButton(QWidget *parent = nullptr) : QPushButton(parent) {}
        bool isChecked() const { return _isChecked; }
        void setChecked(bool checked)
            if (_isChecked == checked) return;
            _isChecked = checked;
            if (checked) setStyleSheet("background-color: rgb(255, 85, 0);");
            else setStyleSheet("");
            emit checkedChanged(checked);
        void checkedChanged(bool checked);
        bool _isChecked;
    #endif // CHECKBUTTON_H

Log in to reply