问题描述
我正在使用 QtCreator 在 C++ 中创建一个 Qt 应用程序。
我知道 CSS 并且为我的应用程序中的元素制作主题并不太难,但是有没有办法制作文件并应用它?
我已经浏览了 Qt Docs,但我似乎无法找到有关此类内容的任何信息。
目前,我正在为每个单独的按钮和内容设置样式,但我可以将它们全部放在一个文件中并立即将其应用于所有内容吗?
解决方法
简单:您只需创建一个文件,例如style.myStyle 在那里你放置所有小部件的样式,包括事件、属性等 然后在应用程序启动时加载文件并将其应用到应用程序
这是一个例子:
#include <QApplication>
#include <QFile>
int main(int argc,char *argv[])
{
QApplication a(argc,argv);
QFile file("./style.myStyle");
file.open(QFile::ReadOnly);
QString styleSheet = QLatin1String(file.readAll());
a.setStyleSheet(styleSheet);
MainWindow w;
w.show();
return a.exec();
}
现在在 style.myStyle 文件中你可以做任何你想做的事情,例如
QPushButton
{
background-color: white;
border-style: outset;
border-width: 2px;
border-radius: 10px;
border-color: beige;
font: bold 14px;
min-width: 10em;
min-height: 20em;
padding: 6px;
}
QPushButton:pressed
{
background-color: rgb(224,0);
border-style: inset;
}
QFrame,QLabel,QToolTip
{
border: 2px solid green;
border-radius: 2px;
padding: 1px;
}
该代码产生这样的窗口:
注意:
不要忘记验证文件是否存在等等