Search code examples
c++qtqt5qtstylesheetsqpushbutton

How to programmatically change style sheet of buttons in Qt?


I have so many buttons on a dialog and I want to change style sheets of them under some conditions. Button object names are like below:
btn_1
btn_2
btn_3
..
btn_20


When I clicked one of these numerical buttons and later to another simple button, I want to change first clicked numerical button style sheet. How can I access that selected numerical button?

Edit: What I mean by picture
buttons


I am trying to set colors of left column buttons (has numerically ordered object names) with right column buttons. User will be clicked numerical buttons first and then color named buttons.


Solution

  • You have to use the setStyleSheet method but you have to keep the reference of the button pressed, and that can be done using the sender method that returns the object that emitted the signal.

    #include <QtWidgets>
    
    class MainWindow: public QMainWindow{
        Q_OBJECT
    public:
        MainWindow(QWidget *parent=nullptr):
            QMainWindow(parent),
            current_button(nullptr)
        {
            QWidget *widget = new QWidget;
            setCentralWidget(widget);
            QHBoxLayout *hlay = new QHBoxLayout(widget);
            QVBoxLayout *number_lay = new QVBoxLayout;
            QVBoxLayout *color_lay = new QVBoxLayout;
            hlay->addLayout(number_lay);
            hlay->addLayout(color_lay);
    
            for(int i=0; i<20; i++){
                QPushButton *button = new QPushButton(QString("btn_%1").arg(i+1));
                connect(button, &QPushButton::clicked, this, &MainWindow::number_clicked);
                number_lay->addWidget(button);
            }
            color_lay->addStretch();
            for(const QString & colorname: {"Red", "Green", "Blue"}){
                QPushButton *button = new QPushButton(colorname);
                connect(button, &QPushButton::clicked, this, &MainWindow::color_clicked);
                color_lay->addWidget(button);
                button->setProperty("color", colorname.toLower());
                button->setStyleSheet(QString("background-color: %1").arg(colorname));
            }
            color_lay->addStretch();
        }
    private slots:
        void number_clicked(){
            current_button = qobject_cast<QPushButton *>(sender());
        }
        void color_clicked(){
            if(current_button){
                QString colorname = sender()->property("color").toString();
                current_button->setStyleSheet(QString("background-color: %1").arg(colorname));
            }
        }
    private:
        QPushButton *current_button;
    };
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MainWindow w;
        w.show();
    
        return a.exec();
    }
    #include "main.moc"
    

    enter image description here