QT之插件Plugin生成与使用
简述
有时候,我们在做一个应用程序的时候,并不希望我们生成的软件仅仅是一个EXE文件,而是拆分成各个模块,越细越好。在未来更新发布中,都是非常的便利,我们更新的只是其中某一小部分,而不是整个应用程序。(说到这里,我们看代码吧)
插件生成
//我们先定义一个接口头文件plugindemoplugin.h
QT_BEGIN_NAMESPACE
class QtPluginDemoInterface
{public:virtual ~QtPluginDemoInterface() {}//接口中声明一个打印函数virtualvoid printMessage(const QString& message) =0;
};#define QDesignerCustomWidgetInterface_iid "org.qt-project.QtPluginDemoInterface"
Q_DECLARE_INTERFACE(QtPluginDemoInterface, QDesignerCustomWidgetInterface_iid)
QT_END_NAMESPACE
//派生类头文件plugindemo.h#include "plugindemoplugin.h"
class pluginDemo :public QObject, QtPluginDemoInterface
{
Q_OBJECT
Q_PLUGIN_METADATA(IID"org.qt-project.Qt.QtPluginDemoInterface" FILE"plugindemoplugin.json")
Q_INTERFACES(QtPluginDemoInterface)public:voidprintMessage(const QString& message)override;
};
//plugindemo.cpp//在定义一个派生类去实现我们基类中的接口,编译生成库文件void pluginDemo::printMessage(const QString& message)
{//在派生类中实现打印函数
qDebug() <<"---------------This is QtPluginDemoInterface Demo Test--------------" << message;
}
接下来,我们在我们的UI主程序中加载此插件
//plugintest.h#include <QtWidgets/QMainWindow>#include "ui_plugintest.h"
class QtPluginDemoInterface;
class PluginTest :public QMainWindow
{
Q_OBJECTpublic:PluginTest(QWidget *parent =0);private:
Ui::PluginTestClass ui;
QtPluginDemoInterface * m_echoInterface;bool loadPlugin();
};
//plugintest.cpp
PluginTest::PluginTest(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
loadPlugin();
connect(ui.pushButton, &QPushButton::clicked, [this](){
m_echoInterface->printMessage("123456789");
});
}bool PluginTest::loadPlugin()
{
QDir pluginsDir(qApp->applicationDirPath());//这里我新建了plugins文件夹,把上面生成的dll文件放到此文件夹下
pluginsDir.cd("plugins");//加载当前文件夹下的库文件foreach(QString fileName, pluginsDir.entryList(QDir::Files)) {
QPluginLoader pluginLoader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = pluginLoader.instance();if (plugin) {
m_echoInterface = qobject_cast<QtPluginDemoInterface *>(plugin);if (m_echoInterface)returntrue;
}
}returnfalse;
}
效果图
结尾
只为记录,只为分享! 愿所写能对你有所帮助。GoodGoodStudy,DayDayUp!