在实际应用中,会存在这样的需求:同一个按钮根据不同的逻辑显示不同的样式,比如,成功显示绿色、失败显示红色、进行中显示黄色。
有3种实现方式:
第一种方式:每次修改逻辑时直接设置stylesheet即可
成功时修改样式为
btn->setStyleSheet("QPushButton{background-color:green;}");
失败时修改样式为
btn->setStyleSheet("QPushButton{background-color:red;}");
进行中时修改样式为
btn->setStyleSheet("QPushButton{background-color:yellow;}");
第二种方式:动态增加属性,配置好所有状态的样式表并加载,然后通过修改属性的方式来实现
//=========第一步,设置样式
/*可以用该窗口的this方式设置,这样该窗口所有的继承自QPushButton的都拥有这个样式
**也可以使用qApp去设置,这样所有的窗口QPushButton都有这个样式。
this->setStyleSheet(
"QPushButton[state='ok'] {background-color:green;}"
"QPushButton[state='fail'] {background-color:red;}"
"QPushButton[state='running'] {background-color:yellow;}");
*/
//此情况下,只有btn这个对象独享该样式
btn->setStyleSheet(
"QPushButton[state='ok'] {background-color:green;}"
"QPushButton[state='fail'] {background-color:red;}"
"QPushButton[state='running'] {background-color:yellow;}");
//=====第二步,在需要的位置根据逻辑设置自定义动态属性即可
btn->setProperty("state","ok"); //成功时设置此动态属性值
btn->setProperty("state","fail"); //失败时设置此动态属性值
btn->setProperty("state","running"); //进行时设置此动态属性值
btn->setProperty("state",QVariant());//常态时设置此动态属性值
//设置完上述动态属性值后,我们发现,样式可能没有效果,这是因为样式没有刷新,需要强制刷新一下。
//另外还发现:如果使用 btn->setStyleSheet,则需要btn->style()去polish,否则不起作用
// 如果使用this->setStyleSheet或者qApp,则用 this->style()或者btn->style()都可以。
//所以统一就用对象本身比较好
btn->style()->unpolish(btn); //清除旧的样式
btn->style()->polish(btn); //更新为新的样式
第三种方式:通过修改类的方式来实现动态切换样式
//=========第一步,设置样式
//具体用对象本身还是this抑或是qApp,请参考上一个说明
btnAA->setStyleSheet(
".GreenState {background-color:green;}"
".RedState {background-color:red;}"
".YellowState {background-color:yellow;}");
//=====第二步,在需要的位置根据逻辑设置属性类名
btn->setProperty("class","GreenState");
btn->setProperty("class","RedState");
btn->setProperty("class","YellowState");
btn->setProperty("class",QVariant());
//第三步,具体说明请参考上一个说明
btn->style()->unpolish(btn);
btn->style()->polish(btn);
这3种方式中:
第一种方式是将样式直接写到代码里面 ,虽然也可以通过配置文件的方式(比如json)来操作,但是很零散。
第二种和第三种方式可以将样式写到css文件中,比较友好,方便样式管理。