在 Qt 项目中新建一个或使用已有的 Qt Resource File
,在资源文件下面新建一个普通文件,命名为 Light.qss
:html
为 Light.qss
添加以下内容:git
这里是模仿 bootstrap 的样式格式,为 QPushButton 添加几种情景色,熟悉以后能够自行添加更多的情景模式。github
编写 QSS 样式文件时推荐使用 VSCODE(由于 QtCreator 彷佛不支持高亮显示该类型的文件,可能有插件能够支持),上图就是从 VSCODE 中截得图,安装 Qt for Python
这个插件后就能正常高亮这个文件了。bootstrap
在 Qt 中导入样式的方法有不少种,能够直接设置 QApplication 对象的 style:app
qApp->setStyleSheet("QLineEdit { background-color: yellow }");
或者对某个 QWidget 对象设置 style:函数
myDialog->setStyleSheet("QLineEdit { background-color: yellow }");
你能够像我同样作,在 MainWindow 的构造函数中添加以下语句:测试
// MainWindow::MainWindow() ui->setupUi(this); QFile styleFile(":/Light.qss"); styleFile.open(QFile::ReadOnly); QString style = QString::fromUtf8(styleFile.readAll()); setStyleSheet(style); styleFile.close();
MainWindow 的 ui 文件很简单,仅有 3 个按钮:ui
若是直接运行这个程序,你会看到按钮仍是和上面的图片中所显示的那样,没有任何情景色的变化。咱们须要给各个按钮设置不一样的属性:this
// set property ui->primary->setProperty("variable", "primary"); ui->success->setProperty("variable", "success"); ui->warning->setProperty("variable", "warning");
再运行程序,图片就变成这样的多种颜色风格的了:插件
上面更改完按钮的样式后,实际上图片样式就固定下来了,作个小测试:
void MainWindow::on_primary_clicked() { if(ui->primary->property("variable").toString() == "primary") { ui->primary->setProperty("variable", "success"); } else { ui->primary->setProperty("variable", "primary"); } }
添加这段槽函数代码,执行程序,点击上面第一个按钮,颜色并不会变化。如下是摘自官方的说明
Limitations
There are limitations to using this trick. The main one is that the style will not update itself automatically when the value of a property referenced from the style sheet changes. Instead, you must manually trigger an update of the visual appearance of a widget when a styled property changes.
为了动态改变按钮的样式,咱们还要添加一些代码:
ui->primary->style()->unpolish(ui->primary); ui->primary->style()->polish(ui->primary);
运行程序,再次点击第一个按钮,能够看到以下图所示的内容,第一个按钮变成了绿色:
再点击一次,它又会变成蓝色。这样就达到了动态改变样式的目的。
本文首发于 BriFuture 的 我的博客