Qt Q_INIT_RESOURCE 让 dll 动态库使用 qrc 资源文件

版权声明:分享得以延续,交流方知彼此。作者:陈鲁勇 https://blog.csdn.net/CSND_Ayo/article/details/78363645


前言

我们经常会在动态库中使用一些资源文件,例如 qss 文件、 png 文件,以达到美化界面的效果,刚刚使用 Qt 创建动态库的朋友可能会发现, 在代码中无法添加 qrc 资源文件中的图片资源。
显然,这会给我们带来很多麻烦,今天我们就来解决这些麻烦。

Q_INIT_RESOURCE

Q_INIT_RESOURCE 初始化qrc资源,我们简单的看下官方的介绍文档,以及使用的简单 Demo。

Qt Doc

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:

  Q_INIT_RESOURCE(myapp);

If the file name contains characters that cannot be part of a valid C++ function name (such as '-'), they have to be replaced by the underscore character ('_').
Note: This macro cannot be used in a namespace. It should be called from main(). If that is not possible, the following workaround can be used to init the resource myapp from the function MyNamespace::myFunction:

inline void initMyResource() {
    Q_INIT_RESOURCE(myapp); 
}

  namespace MyNamespace {
      ...

      void myFunction() {
          initMyResource();
      }
  }

See also Q_CLEANUP_RESOURCE() and The Qt Resource System. 

Qt Demo


//- project tree
//    mainwindow.h
//    
//    main.cpp
//    mainwindow.cpp
//
//    res.qrc


int main(int argc, char *argv[]) {
    Q_INIT_RESOURCE(res);

    QApplication a(argc, argv);
    CommonHelper::setStyle(":/qss/black");
    SRMainWidget w;
    w.show();

    return a.exec();
}

说明

Q_INIT_RESOURCE 可以加载关键字为参数的 qrc 文件,

    Q_INIT_RESOURCE(res);

上述代码就是加载本地名为 res.qrc 的资源文件。

在接下来中使用 res.qrc 作为本工程中的资源引用文件。

下载

过几天我会提供 demo 供大家简单下载

猜你喜欢

转载自blog.csdn.net/CSND_Ayo/article/details/78363645