QSS为Qt程序添加不一样的样式

添加 QSS 样式文件

在 Qt 项目中新建一个或使用已有的 Qt Resource File,在资源文件下面新建一个普通文件,命名为 Light.qss

Light.qss 添加如下内容:

这里是模仿 bootstrap 的样式格式,为 QPushButton 添加几种情景色,熟悉之后可以自行添加更多的情景模式。

编写 QSS 样式文件时推荐使用 VSCODE(因为 QtCreator 似乎不支持高亮显示该类型的文件,可能有插件可以支持),上图就是从 VSCODE 中截得图,安装 Qt for Python 这个插件后就能正常高亮这个文件了。

导入 QSS 样式

在 Qt 中导入样式的方法有很多种,可以直接设置 QApplication 对象的 style:

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 个按钮:

如果直接运行这个程序,你会看到按钮还是和上面的图片中所显示的那样,没有任何情景色的变化。我们需要给各个按钮设置不同的属性:

// 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);

运行程序,再次点击第一个按钮,可以看到如下图所示的内容,第一个按钮变成了绿色:

再点击一次,它又会变成蓝色。这样就达到了动态改变样式的目的。


Demo Project 的 github 地址

本文首发于 BriFuture 的 个人博客

参考

  1. Dynamic_Properties_and_Stylesheets
  2. customizing-using-dynamic-properties
posted @ 2019-03-15 20:24  brifuture  阅读(1429)  评论(0编辑  收藏  举报