Qt加载qss文件
阅读原文时间:2021年04月24日阅读:1

试验环境:visual studio 2015,Qt5.7.1

1.在自己建立的qt项目的Resource目录下新建一个文本文件,改名为*.qss

例如下面随便编写一个qss,试验运行后是否生效

mainwindow.qss

QDockWidget{
    border: 20px solid rgb(255,0,0);
    background: blue;
}
QWidget{
    border: 1px solid rgb(255,0,0);
}

2.在vs中将该文件添加到项目的Resource Files筛选器下

3.打开qrc资源文件(我的资源文件名为org_gui_mainwindow.qrc,这个名字后面要用)

4.根据自己的qss文件路径添加qss文件信息到qrc文件,写相对路径的话就是以qrc文件所在目录为当前路径

org_gui_mainwindow.qrc

<RCC>
    <qresource prefix="org_gui_mainwindow">
      <file>Resources/mainwindow.qss</file>
    </qresource>
</RCC>

添加Dock窗体以及其他部分就省略了,直接看加载qss文件部分

#include "org_gui_mainwindow.h"
#include <QtWidgets/QApplication>
#include <QFile>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    //Q_INIT_RESOURCE(org_gui_mainwindow);

    QFile qss("Resources/mainwindow.qss");
    qss.open(QFile::ReadOnly);
    qApp->setStyleSheet(qss.readAll());
    qss.close();


    org_gui_mainwindow w;
    w.show();
    return a.exec();
}

显示结果如下:

顺带一提上面的Q_INIT_RESOURCE(name),这里传入的参数和我定义的类org_gui_mainwindow是相同的,但是这里传入的资源文件应该是上面所提到的org_gui_mainwindow.qrc,只是因为新建项目时qrc文件默认就和自动生成的qt窗体控制类同名

Q_INIT_RESOURCE(name)在这里起到的作用是初始化qrc文件指定的所有资源,也就是你通常要使用图片等资源时就可以使用该方法对资源进行加载

void Q_INIT_RESOURCE(name)官方文档说明如下:

Initializes the resources specified by the .qrc file with the specified base name. Normally, when resources are built as part of the application, the resources are loaded automatically at startup. The Q_INIT_RESOURCE() macro is necessary on some platforms for resources stored in a static library.

For example, if your application's resources are listed in a file called myapp.qrc, you can ensure that the resources are initialized at startup by adding this line to your main() function.


参考文献:Qt加载QSS文件

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章