Qt5的外掛機制(7)--外掛開發示例程式碼(Lower-level API)
阿新 • • 發佈:2019-02-04
外掛程式碼
介面類標頭檔案 MyPluginInterface.h
- #ifndef INTERFACES_H
- #define INTERFACES_H
- #include <QtPlugin>
- #define QtPluginDemo_iid "org.qt-project.Qt.PluginDemo"
- class MyPluginInterface
- {
- public:
- virtualint add(int,int) = 0 ; // 正確寫法
-
// virtual int add(int,int); // 不太妥的寫法(雖然這也是正確的虛擬函式宣告語句)
- // 注:介面類中的虛擬函式都應有實體,或設定為0(推薦),這樣
- // C++的編譯器才能為介面類生成虛擬函式表。否則,如果沒有實現
- // 介面類的虛擬函式也沒有將其設為0,程式在在連結時可能會失敗,
- // 或者連結成功但最後生成的庫無法載入(庫中有未定義的符號)
- };
- Q_DECLARE_INTERFACE ( MyPluginInterface, QtPluginDemo_iid ) ;
- #endif
外掛標頭檔案 MyPlugin.h
- #ifndef MYPLUGIN__H
- #define MYPLUGIN__H
-
#include <QObject>
- #include <QDebug>
- #include "MyPluginInterface.h"
- class MyPlugin : public QObject, public MyPluginInterface
- {
- Q_OBJECT
- Q_PLUGIN_METADATA ( IID QtPluginDemo_iid FILE"MyPlugin.json")
- Q_INTERFACES(MyPluginInterface)
- public:
- int add(int,int);
- };
- #endif
外掛原始檔 MyPlugin.cpp
- #include "MyPlugin.h"
- int MyPlugin::add(int a , int b)
- {
- return a+b ;
- }
- #include "moc_MyPlugin.cpp"
JSON檔案 MyPlugin.json,本示例中該檔案是空的。
工程檔案 MyPlugin.pro
- TEMPLATE = lib
- CONFIG += plugin console
- QT += core
- HEADERS = MyPlugin.h MyPluginInterface.h
- SOURCES = MyPlugin.cpp
- OTHER_FILES = MyPlugin.json
- TARGET = MyPlugin
- DESTDIR = ./
- INCLUDEPATH += ./
- # install
- target.path = ./install
- INSTALLS += target
應用程式程式碼
介面類標頭檔案 MyPluginInterface.h,該檔案與外掛程式碼中的一致。
主程式檔案 main.cpp
- #include "MyPluginInterface.h"
- #include <QtPlugin>
- #include <QApplication>
- #include <QWidget>
- #include <QPluginLoader>
- #include <QString>
- #include <QtDebug>
- int main(int argc, char *argv[])
- {
- QApplication app(argc, argv);
- QWidget w;
- QObject* object ;
- w.show();
- app.addLibraryPath(QString("../MyPlugin/install")); // 新增庫路徑
- // 載入外掛,取得例項
- QPluginLoader l(QString("MyPlugin")) ;
- //QPluginLoader l(QString("libMyPlugin.so")) ;
- if ( (object=l.instance()) != NULL )
- {
- qDebug("plugin loaded .");
- // 使用外掛
- int a = 14 , b = 23 ;
- MyPluginInterface* plugin = qobject_cast<MyPluginInterface*>(object) ;
- if (plugin)
- qDebug("%d + %d = %d",a,b,plugin->add(a,b));
- }
- else
- {
- qDebug("failed to load plugin !! ");
- QString errorStr = l.errorString();
- qDebug()<<errorStr;
- }
- return app.exec();
- }
MyApp.pro
- ######################################################################
- # Automatically generated by qmake (3.0) ?? 11? 19 02:26:33 2014
- ######################################################################
- TEMPLATE = app
- QT += gui core widgets
- CONFIG += console
- TARGET = MyApp
- INCLUDEPATH += .
- # Input
- HEADERS += MyPluginInterface.h
- SOURCES += main.cpp
from: http://blog.csdn.net/newthinker_wei/article/details/41338447