您的位置:首页 > 编程语言 > Qt开发

Qt的插件机制

2010-11-02 20:38 501 查看
使用Qt插件和编写Qt插件需要注意:

Making an application extensible through plugins involves the following steps:

Define a set of interfaces (classes with only pure virtual functions) used to talk to the plugins.

Use the Q_DECLARE_INTERFACE() macro to tell Qt's meta-object system about the interface.

Use QPluginLoader in the application to load the plugins.

Use qobject_cast() to test whether a plugin implements a given interface.

Writing a plugin involves these steps:

Declare a plugin class that inherits from QObject and from the interfaces that the plugin wants to provide.

Use the Q_INTERFACES() macro to tell Qt's meta-object system about the interfaces.

Export the plugin using the Q_EXPORT_PLUGIN2() macro.

Build the plugin using a suitable .pro file

Qmediaserviceproviderplugin.h

struct Q_MULTIMEDIA_EXPORT QMediaServiceProviderFactoryInterface : public QFactoryInterface
{
...
};
#define QMediaServiceProviderFactoryInterface_iid /
"com.nokia.Qt.QMediaServiceProviderFactoryInterface/1.0"
Q_DECLARE_INTERFACE(QMediaServiceProviderFactoryInterface, QMediaServiceProviderFactoryInterface_iid)
struct Q_MULTIMEDIA_EXPORT QMediaServiceSupportedDevicesInterface
{
...
};
#define QMediaServiceSupportedDevicesInterface_iid /
"com.nokia.Qt.QMediaServiceSupportedDevicesInterface/1.0"
Q_DECLARE_INTERFACE(QMediaServiceSupportedDevicesInterface, QMediaServiceSupportedDevicesInterface_iid)

class Q_MULTIMEDIA_EXPORT QMediaServiceProviderPlugin : public QObject, public QMediaServiceProviderFactoryInterface
{
Q_OBJECT
Q_INTERFACES(QMediaServiceProviderFactoryInterface:QFactoryInterface)
public:
...
};


Qstreamerplayerplugin.h

class QGstreamerServicePlugin : public QMediaServiceProviderPlugin, public QMediaServiceSupportedDevicesInterface
{
Q_OBJECT
Q_INTERFACES(QMediaServiceSupportedDevicesInterface)
public:
...
private:
...
};


Qsteamerplayerplugin.cpp

#include "qstreamerplayerplugin.h"
//Implementation
...
Q_EXPORT_PLUGIN2(qtmedia_gstengine, QGstreamerServicePlugin);


Qstreamerplayerplugin继承并实现了两个抽象类。Q_INTERFACES的作用是将所实现的接口通知元类型系统,而Q_EXPORT_PLUGIN2(PluginName, ClassName)指明了插件名和根类名,表示向外部声明本插件的“身份证。

QPluginLoader可以在运行时载入一个插件,它在构造函数中指明一个包含插件的文件(shared library)并用load()导入,其最重要的功能是可以用instance()直接访问这个插件的root component,而不用人工地分析这个文件。而所谓的root component其实就是插件中使用了Q_EXPORT_PLUGIN2的那个类,instance()的返回值就是指向这个类的实例的QObject指针。

一旦插件被导入,它会一直驻留在内存中直到所有的QPluginLoader实例被unload或应用程序终止。你可以调用unload()来试图释放一个插件,但是只有一个插件的所有实例都被调用unload(),插件才会被真正释放。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: