定义接口
如上图所示,先要定义一个插件类,然后使用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.