Search code examples
c++qtqwidget

How to add buttons to a main window by programmatically in Qt and change styles them by use css file?


I will add two buttons to the a dialog and I want to change style sheets of them by use css file:

enter image description here

I also define the buttons as follows that didn't work:

sendButton = new QPushButton();
sendButton->setVisible(true);
sendButton->setText("sendButton");
sendButton->setStyleSheet("QPushButton#sendButton {\n"
                          "background-color: red;\n"
                          "border-style: outset;\n"
                          "border-width: 2px;\n"
                          "border-radius: 10px;\n"
                          "border-color: beige;\n"
                          "font: bold 14px;\n"
                          "min-width: 10em;\n"
                          "padding: 6px;\n"
                          "}\n"
                          "QPushButton#reciveButton {\n"
                          "background-color: green;\n"
                          "border-style: outset;\n"
                          "border-width: 2px;\n"
                          "border-radius: 10px;\n"
                          "border-color: beige;\n"
                          "font: bold 14px;\n"
                          "min-width: 10em;\n"
                          "padding: 6px;\n"
                          "}\n");


ui->horizontalLayout->addWidget(sendButton);

Solution

  • If you are using the ID Selector QPushButton#objectName, be sure to also set the object name for your QPushButton, otherwise the selector will not work

    sendButton = new QPushButton();
    sendButton->setVisible(true);
    sendButton->setText("sendButton");
    
    sendButton->setObjectName("sendButton"); /* Set the object name */
    
    sendButton->setStyleSheet(...);
    
    

    Hope this helps =)