Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Qt plugin 的创建和动态加载

From Wiki
Jump to: navigation, search
Article Metadata
Code ExampleCompatibility
Platform(s):
Symbian
Article
Created: liuting (21 Dec 2011)
Last edited: renlin (12 Jul 2012)


Contents

介绍

plug in 是一个实现了一个或多个接口的DLL,下面我们将介绍在QT中如何创建PLUG IN 和如何动态加载PLUG IN


创建plug in

首先定义一个Interface,并且用Q_DECLARE_INTERFACE宏告知qt meta-object system有这 样一个interface,代码如下:

class EchoInterface
{
public:
virtual ~EchoInterface() {}
virtual QString echo(const QString &message) = 0;
};
QT_BEGIN_NAMESPACE
Q_DECLARE_INTERFACE(EchoInterface,
"com.trolltech.Plugin.EchoInterface/1.0");
QT_END_NAMESPACE

其次定义一个plugin的类,必须从interface继承,并在.h用Q_INTERFACE告诉meta-object system我们的类支持这样的interface,具体代码如下:

class EchoPlugin : public QObject, EchoInterface
{
Q_OBJECT
Q_INTERFACES(EchoInterface)
 
public:
QString echo(const QString &message);
};

实现这个类并用Q_EXPORT_PLUGIN2(pluginName,class)导出这个plugin,具体代码如下:

Q_EXPORT_PLUGIN2(echoplugin, EchoPlugin);

建立合适的.pro文件来编译这个plugin,具体代码如下:

TEMPLATE        = lib
CONFIG += plugin
INCLUDEPATH += ../echowindow
HEADERS = echoplugin.h
SOURCES = echoplugin.cpp
TARGET = $$qtLibraryTarget(echoplugin)
DESTDIR = ../plugins

其中DESTDIR 指定 DLL 生成的路径,TARGET TARGET的内容必须和Q_EXPORT_PLUGIN2中的pluginName一致; 这样我们就创建了一个PLUG IN,接下来我们看下如何动态加载PLUG IN 。

动态加载plug in

我们通过QPluginLoader 来加载 plug in , 具体代码如下:

QDir pluginsDir(qApp->applicationDirPath());
#if defined(Q_OS_WIN)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
if (pluginsDir.dirName() == "MacOS") {
pluginsDir.cdUp();
pluginsDir.cdUp();
pluginsDir.cdUp();
}
#endif
pluginsDir.cd("plugins");
foreach (QString fileName, pluginsDir.entryList(QDir::Files)) {
QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName));
qDebug()<<pluginsDir.absoluteFilePath(fileName);
pluginLoader.load();
QObject *plugin = pluginLoader.instance();
if (plugin) {
echoInterface = qobject_cast<EchoInterface *>(plugin);
if (echoInterface)
return true;
}
}

这样我们就完成了 一个PLUG IN 的创建和调用。

代码示例

File:Echoplugin.zip

相关链接

This page was last modified on 12 July 2012, at 01:49.
398 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×