QT生成资源文件动态库

简述

若要生成资源文件动态库则需要在资源文件动态库项目的属性-生成事件/生成后事件/命令行中加入$(QTDIR)\bin\rcc.exe --binary 资源文件名.qrc --output $(SolutionDir)\$(Platform)\$(Configuration)\资源文件名.rcc,然后在项目中使用QResource::registerResource("Resource.rcc")进行资源文件的注册使用。

开发环境

Qt 5.12.4 + VS2017

解决方案代码

包含资源文件动态库项目ResourceDll和主项目Test

资源文件动态库项目ResourceDll代码

1、头文件StarStudio.ResourceManager.h

#ifndef STARSTUDIO_RESOURCEMANAGER_H
#define STARSTUDIO_RESOURCEMANAGER_H

#include "StarStudio.Defines.h"
#include <QObject>

class STARSTUDIODLL_EXPORT ResourceManager : public QObject
{
    
    
public:
	static ResourceManager* Instance();
	~ResourceManager();

	void RegisterResource();
	void UnregisterResource();

private:
    ResourceManager(QObject *parent = nullptr);

private:
	static ResourceManager *m_pInstance;
};
#endif

2、源文件StarStudio.ResourceManager.cpp

#include "StarStudio.ResourceManager.h"
#include <QResource>

ResourceManager *ResourceManager::m_pInstance = nullptr;
ResourceManager::ResourceManager(QObject *parent)
	: QObject(parent)
{
    
    
}

ResourceManager::~ResourceManager()
{
    
    
}

ResourceManager* ResourceManager::Instance()
{
    
    
	//单例模式方便使用
	if (m_pInstance == nullptr)
	{
    
    
		m_pInstance = new ResourceManager;
	}

	return m_pInstance;
}

void ResourceManager::RegisterResource()
{
    
    
	//注册资源文件,rcc文件是在生成后事件中由qrc文件生成
	QResource::registerResource("Resource.rcc");
}

void ResourceManager::UnregisterResource()
{
    
    
	QResource::unregisterResource("Resource.rcc");
}

3、添加资源文件Resource.qrc,将图标等文件加入到qrc资源文件,如下
在这里插入图片描述

4、项目配置类型选择动态库(.dll),设置生成后事件属性,如下
在这里插入图片描述

主项目Test代码

1、源文件main.cpp

#include "StarStudio.MainWindow.h"
#include <QtWidgets/QApplication>

int main(int argc, char *argv[])
{
    
    
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

2、头文件StarStudio.MainWindow.h

#ifndef STARSTUDIO_MAINWINDOW_H
#define STARSTUDIO_MAINWINDOW_H

#include <QtWidgets/QMainWindow>

class MainWindow : public QMainWindow
{
    
    
    Q_OBJECT

public:
    MainWindow(QWidget *parent = Q_NULLPTR);
	~MainWindow();
};
#endif

2、源文件StarStudio.MainWindow.cpp

#include "StarStudio.MainWindow.h"
#include "StarStudio.ResourceManager.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    
    
	ResourceManager::Instance()->RegisterResource(); //资源文件动态库的资源注册方法
	this->setWindowIcon(QIcon(":/Resource/Icon/Logo")); //使用图标资源设置窗口图标
}

MainWindow::~MainWindow()
{
    
    
}

3、项目属性需要添加资源文件动态库的头文件路径和设置附加依赖项即ResourceDll.lib

效果

在这里插入图片描述
稍加整理方便大家参考,如有错误请指正,谢谢!

猜你喜欢

转载自blog.csdn.net/Staranywhere/article/details/109267146