0

Related Qusetions:

There are at least 3 ways to solve the problem:

// 1st 
QColor color = ui->toolButton->palette().color(QWidget::backgroundRole());
// 2nd
QColor color = ui->toolButton->palette().background().color();
// 3rd
QColor color = colorSetting = ui->toolButton->palette().color(QPalette::Window);

Update: sorry I have made some mistakes, both of the following ways work well.


Raw Qusetion:

I have tried

QColor color = ui->toolButton->palette().background().color();

and

QColor color = colorSetting = ui->toolButton->palette().color(QPalette::Window);

both got QColor(ARGB 1, 0.941176, 0.941176, 0.941176), not the right color I want.

The background color is set by editing mainwindow.ui, change stylesheet of toolButton to background-color: rgb(255, 170, 255);

image of my toolButton

and for pyQt, see here How to get the background color of a button or label (QPushButton, QLabel) in PyQt

Community
  • 1
  • 1
応振强
  • 266
  • 3
  • 12

1 Answers1

0

Your linked question is incorrect about the color role used by buttons. You are looking for QPalette::Button as your ColorRole.

QColor color = ui->toolbutton->palette()->color(QPalette::Button);

Be are that this color may not represent the background painted for the tool button. Some styles use gradients and QPalette stores brushes, not colors. Call QPalette::button() to retrieve the button background brush.

I suspect you intend to change the background color. You can call setBrush() to set it:

//Create a solid brush of the desired color
QBrush brush(someColor);
//Get a copy of the current palette to modify
QPalette pal = ui->toolbutton->palette();
//Set all of the color roles but Disabled to our desired color
pal.setBrush(QPalette::Normal, QPalette::Button, brush);
pal.setBrush(QPalette::Inactive, QPalette::Button, brush);
//And finally set the new palette
ui->toolbutton->setPalette(pal);
jonspaceharper
  • 4,207
  • 2
  • 22
  • 42