Search code examples
c++qtqtstylesheetsqpushbutton

Changing color of a pushButton in QT


I want to Change the Color of a pushButton in QT after the button is clicked. The Problem is that when I have multiple Buttons all the pushbButton`s Colors Change. How can I make only the one i clicked on Change? PS: I am a beginner so it would be really nice if you could explain your solution in Detail, sry :D.

My Code:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}

int i=1;

void MainWindow::on_pushButton_clicked()
{
    if((i==1))
    {
        setStyleSheet("QPushButton { background-color: grey; }\n"
                      "QPushButton:enabled { background-color: rgb(200,0,0); }\n");
        i=i+1;

    }
    else
    {
        if((i==2))
        {
            setStyleSheet("QPushButton { background-color: grey; }\n"
                          "QPushButton:enabled { background-color: rgb(0,200,0); }\n");
         i=i+1;
        }
        else
        {
            setStyleSheet("QPushButton { background-color: grey; }\n"
                          "QPushButton:enabled { background-color: rgb(0,0,200); }\n");
            i=i-2;
        }
    }

}


Solution

  • How can I make only the one i clicked on Change? you set the property to the button instance then:

    call the set style in that button: ui->pushButton->

    like doing:

    void MainWindow::on_pushButton_clicked()
    {
        if((i==1))
        {
            ui->pushButton->setStyleSheet("QPushButton { background-color: grey; }\n"
                          "QPushButton:enabled { background-color: rgb(200,0,0); }\n");
            i=i+1;
        }
        ....
        ...