February 11, 2012

TheDestroyer TheDestroyer
Lab Rat
145 posts

How to change a Button colour

 

Hello guys,

I searched everywhere for the answer to this question. But the answers I found are either too confusing or don’t work. I want a single serial code to change the color of a button while the window is running.

I have an OpenGL application, and I want the colour to be taken from a QColorDialog and then colour the background of my OpenGL scene, and meanwhile colour the button to show the user what colour chosen (I think you know what I mean).

Here’s the code I’m currently using. The code colours the background behind the button. I want the button itself to be coloured or to have a small section coloured inside it, like we see in all painting programs.

  1.     QPushButton *backgroundColourButton;
  2.     QColor *backgroundColour;
  3.     backgroundColour->setRgb(0,0,0); //example colour, I could later manage to utilize this variable with a QColorDialog
  4.     QPalette Pal(palette());
  5.     Pal.setColor(QPalette::Button, backgroundColour->rgb());
  6.     backgroundColourButton->setAutoFillBackground(true);
  7.     backgroundColourButton->setPalette(Pal);

Thank you for any efforts :)

5 replies

February 11, 2012

Volker Volker
Robot Herder
5428 posts

Easiest way would be to use a style sheet on the button:

  1. backgroundColourButton->setStyleSheet("background-color: red");

BTW – according to a talk of Girish Ramakrishnan (one of the original developers of Qt widget style sheets) at DevDays 2006, it was exactly the need of “making a red push button” that led to the introduction of Qt style sheets eventually :-)

February 11, 2012

TheDestroyer TheDestroyer
Lab Rat
145 posts

But is it possible to get the colour as string from a QColor object? this would solve my problem!

February 11, 2012

Volker Volker
Robot Herder
5428 posts

Of course:

  1. QColor col = QColorDialog::getColor(Qt::white, this);
  2. if(col.isValid()) {
  3.     QString qss = QString("background-color: %1").arg(col.name());
  4.     ui->pushButton->setStyleSheet(qss);
  5. }

Although, the style of the button changes for me, i.e. the rounded box on the Mac is replaced by a plain rectangle.

February 11, 2012

TheDestroyer TheDestroyer
Lab Rat
145 posts

Thanks a lot :-)

February 11, 2012

Volker Volker
Robot Herder
5428 posts

No prob, you’re welcome!

 
  ‹‹ Automatic resizing of window      Segmentation fault... [SOLVED] ››

You must log in to post a reply. Not a member yet? Register here!