QPushButton is not changing the background-color proper

╄→尐↘猪︶ㄣ 提交于 2019-12-24 01:19:02

问题


I have a problem with a QPushButton. I use QT 4.8 and the Designer.

I configured the button to be "flat" and "checkable". The button should be red if not checked and green if checked. To style the button I use a stylesheet.

      QPushButton:default{
         background-color: red;
             color: red;
      }

      QPushButton:checked{
         background-color: green;
             color: black;
      }

Now the problem. If the button is unchecked it is gray. When I press the button he turns green like it should. I tried different other pseudo-states, like !checked, or tried to change to a normal button. But it's always the same. In default state the stylesheet isn't working. If I presse, hover or what ever the button it is changing like I want it.

Any body encountered the same problem and has a solution?

To explain it a little bit further. The color attribute is working correct. The text is always red, except I push the button then it's black. So the style sheet is in use but, just the background-color attribute is not working.

I tried different styles, like motif, cde, cleanlooks etc and it's always the same.


回答1:


I found this in QPushButton Class Reference. "This property's default is false. If this property is set, most styles will not paint the button background unless the button is being pressed. setAutoFillBackground() can be used to ensure that the background is filled using the QPalette::Button brush." Because of this I found the following solution.

First of all I kept the style sheet option for checked

     QPushButton:checked{
         background-color: green.
     }

The I used a palette and set the background color and the setAutoFillBackground function.

     palette_red->setColor(window.button->backgroundRole(), QColor(255, 0, 0, 127));
     window.button->setAutoFillBackground(true);
 window.button->setPalette(*palette_red);

I use the toggle signal to catch changes. When the button is toggle is TRUE the style sheet starts working. To not get double (green over red) colors the setAutoFillBackground has to be turned off again.

     window.button->setAutoFillBackground(false);

The not toggled state is nearly the same. I needed to turn on the setAutoFillBackground and set the palette again.

     window.button->setAutoFillBackground(true);
     window.button->setPalette(*palette_red);

It's a solution, it works but I am still open for further inputs.




回答2:


Not all platforms support styled button backgrounds. What platform are you running on? What is the class name of the style in use?

qDebug() << qApp->style()->metaObject()->className();


来源:https://stackoverflow.com/questions/19669385/qpushbutton-is-not-changing-the-background-color-proper

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!