Qt自定义插件使用总结

定义接口

在这里插入图片描述

如上图所示,先要定义一个插件类,然后使用Q_DECLARE_INTERFACE宏定义一个插件接口。其中Q_DECLARE_INTERFACE(ClassName, Identifier)宏的解释如下:

This macro associates the given Identifier (a string literal) to the interface class called ClassName. The Identifier must be unique.

使用插件接口

在这里插入图片描述
在这里插入图片描述

在定义好插件接口后,就可以使用这个插件接口了。需要注意的是使用的步骤是:

  • 声明元数据
  • 告诉qt类实现的接口

做好前两步后,就可以使用了。其中相关宏的解释如下:

Q_PLUGIN_METADATA(…)

This macro is being used to declare meta data that is part of a plugin that instantiates this object.
The macro needs to declare the IID of the interface implemented through the object, and reference a file containing the meta data for the plugin.
There should be exactly one occurrence of this macro in the source code for a Qt plugin.

Q_INTERFACES(…):

This macro tells Qt which interfaces the class implements. This is used when implementing plugins.

加载插件接口

在这里插入图片描述

如上图所示,将编译好的插件库放在指定的位置后,运行主程序,就可以加载插件了。需要注意的是:

  • QPluginLoader类加载插件
  • QObject *QPluginLoader::instance()函数获取所加载插件的根组件对象
  • qobject_cast()函数可以将根组件对象转换为插件对象

其中相关函数的解释如下:

QObject *QPluginLoader::instance():

Returns the root component object of the plugin. The plugin is loaded if necessary. The function returns 0 if the plugin could not be loaded or if the root component object could not be instantiated.
If the root component object was destroyed, calling this function creates a new instance.
The root component, returned by this function, is not deleted when the QPluginLoader is destroyed. If you want to ensure that the root component is deleted, you should call unload() as soon you don’t need to access the core component anymore. When the library is finally unloaded, the root component will automatically be deleted.
The component object is a QObject. Use qobject_cast() to access interfaces you are interested in.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值