Qt加载qss文件

本文介绍如何在Qt项目中加载QSS样式表文件。通过创建QSS文件、配置资源文件及在main函数中设置样式表,实现界面样式的自定义。适用于希望美化Qt应用程序界面的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

试验环境: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文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值