欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > QT通过setProperty设置不同QSS样式

QT通过setProperty设置不同QSS样式

2025/2/8 5:50:35 来源:https://blog.csdn.net/weixin_43246170/article/details/145487194  浏览:    关键词:QT通过setProperty设置不同QSS样式

请添加图片描述
如上切换效果就是通过setProperty来实现切换不同颜色的。
实现以上效果第一步,需要在QSS中做属性处理。

QLabel{color:red;}
QLabel[status="1"]{color:black;}
QLabel[status="2"]{color:white;}
QLabel[status="3"]{color:blue;}
QLabel[status="4"]{color:skyblue;}

第二步,需要调用对应控件的setProperty。

 w->style()->unpolish(w);//卸载属性w->setProperty(name,value);//设置属性w->style()->polish(w);//加载属性w->update();

示例代码:

#include "widget.h"
#include "ui_widget.h"
#include <QStyle>Widget::Widget(QWidget *parent) :QWidget(parent),ui(new Ui::Widget)
{ui->setupUi(this);ui->label->setStyleSheet("QLabel{color:red;}""QLabel[status=\"1\"]{color:black;}""QLabel[status=\"2\"]{color:white;}""QLabel[status=\"3\"]{color:blue;}""QLabel[status=\"4\"]{color:skyblue;}");
}Widget::~Widget()
{delete ui;
}void Widget::on_pushButton_clicked()
{if (ui->label->property("status").toInt() == 1)setProperty(ui->label,"status","2");else if (ui->label->property("status").toInt() == 2)setProperty(ui->label,"status","3");else if (ui->label->property("status").toInt() == 3)setProperty(ui->label,"status","4");else if (ui->label->property("status").toInt() == 4)setProperty(ui->label,"status","0");elsesetProperty(ui->label,"status","1");
}void Widget::setProperty(QWidget *w, const char *name, const QVariant &value)
{w->style()->unpolish(w);w->setProperty(name,value);w->style()->polish(w);w->update();
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com