实现
1、ui定义出样式表
// 在最开始的类中右键 - 样式表
QPushButton#button2[test="true"]{
color:green;}
QPushButton#button2[test="false"]{
color:red;}
2、主类中定义出属性与实现
#define POLISH(widget) (widget->style()->polish(widget))
class Widget : pulib QWidget
{
Q_OBJECT
Q_PROPERTY(bool test READ getTest WRITE setTest)
public:
Widget(QWidget *parent = nullptr) : QWidget(parent){
}
protected:
bool getTest(){
return test;}
void setTest(const bool &b){
test = b;}
protected slots:
// button1点击测试 - button2显示样式
void on_button1_clicked();
{
static bool b = false;
b = !b;
ui.button2->setProperty("test",b);
// 设置完属性想要button2更改样式就必须进行刷新
// 方案1:
ui.button2->style()->polish(ui.button2)
// 方案2 (注意传入为指针,该指针不能为空)
// POLISH(ui.button2);
}
private:
bool test = false;
}
提一句
貌似不需要设置Q_PROPERTY也是可以的哦。只需给对应控件设置属性值即可,哇哦。
参考
可参考Qt属性
关注
微信公众号搜索"Qt_io_"或"Qt开发者中心"了解更多关于Qt、C++开发知识.。
笔者 - jxd