什么是插件
插件(Plug-in,又称addin、add-in、addon或add-on,又译外挂)是一种遵循一定规范的应用程序接口编写出来的程序。其只能运行在程序规定的系统平台下(可能同时支持多个平台),而不能脱离指定的平台单独运行。因为插件需要调用原纯净系统提供的函数库或者数据。很多软件都有插件,插件有无数种。例如在IE中,安装相关的插件后,WEB浏览器能够直接调用插件程序,用于处理特定类型的文件。以上是百度百科中的对插件的描述。
创建Qt创建
- 一种高级API,用于为Qt本身编写插件:自定义数据库驱动程序,图像格式,文本编解码器,自定义样式等。
- 一种用于扩展Qt应用程序的低级API。也就是说扩展我们自己使用Qt编写的程序。这要求应用程序使用 QPluginLoader 检测和加载插件。在这种情况下,插件可以提供任意功能,不限于数据库驱动程序、图像格式、文本编解码器、样式以及扩展Qt功能的其他类型的插件。
例如,如果你想编写一个自定义的QStyle子类,并让Qt应用程序动态加载它,你可以使用第一种方式。
该文章主要通过示例来展示第二种方式创建插件。通过插件扩展应用程序可涉及以下步骤:
在程序端:
- 定义一组接口(只有纯虚函数的类)。
- 使用Q_DECLARE_INTERFACE()宏告诉Qt的元对象系统有关接口的信息。
- 在程序中使用 QPluginLoader加载插件。
- 使用qobject_cast()测试插件是否实现给定的接口。
在插件端:
- 声明一个插件类,该类继承自QObject和插件要提供的接口类。
- 使用Q_INTERFACES()宏告诉Qt的元对象系统有关接口的信息。
- 使用Q_PLUGIN_METADATA()宏导出插件。
示例
示例是在Qt5.9.8 MSVC 2015下运行。
首先创建一个Qt Subdirs Project工程PluginDemo,并添加一个app应用程序端。如下图所示:
然后添加一个appinterface.h的头文件,该类作为插件接口类。
#ifndef APPINTERFACE_H
#define APPINTERFACE_H
#include <QList>
#include <QAction>
class AppInterface
{
public:
virtual ~AppInterface() {}
// 插件的名字
virtual QString name() const = 0;
// 插件返回的QAction列表
virtual QList<QAction *> actions() const = 0;
};
Q_DECLARE_INTERFACE(AppInterface, "plugindemo_app_interface")
#endif // APPINTERFACE_H
在上面的代码中,使用 Q_DECLARE_INTERFACE来注册。
接口类创建好了,我们需要的创建一个插件。在工程上右键,选择New Subproject,选择Library->C++ Library,根据向导创建plugin1。
修改plugin.pro
#-------------------------------------------------
#
# Project created by QtCreator 2023-07-26T17:17:22
#
#-------------------------------------------------
QT += gui widgets
TARGET = plugin1
TEMPLATE = lib
CONFIG += plugin
DEFINES += PLUGIN1_LIBRARY
# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
plugin1.cpp
HEADERS += \
plugin1.h \
plugin1_global.h
target.path = $$OUT_PWD/../bin/plugins
INSTALLS += target
注意其中的CONFIG+=plugin和INSTALL+=target。
实现接口类plugin.h,注意QObject需要放到前面和添加Q_INTERFACES和Q_PLUGIN_METADATA宏
#ifndef PLUGIN1_H
#define PLUGIN1_H
#include <QObject>
#include "../app/appinterface.h"
#include "plugin1_global.h"
class PLUGIN1SHARED_EXPORT Plugin1 : public QObject, public AppInterface
{
Q_OBJECT
Q_INTERFACES(AppInterface)
Q_PLUGIN_METADATA(IID "Plugin1")
public:
Plugin1();
// AppInterface interface
public:
virtual QString name() const override;
virtual QList<QAction *> actions() const override;
};
#endif // PLUGIN1_H
plugin.cpp
#include "plugin1.h"
#include <QMessageBox>
Plugin1::Plugin1()
{
}
QString Plugin1::name() const
{
return "Plugin1";
}
QList<QAction *> Plugin1::actions() const
{
QAction *aboutQt = new QAction;
aboutQt->setText(tr("About Qt"));
connect(aboutQt, &QAction::triggered, this, []{
QMessageBox::aboutQt(nullptr);
});
QList<QAction *> result;
result << aboutQt;
result << new QAction(tr("Test"));
return result;
}
这样我们实现了一个简单的插件,需要在构建步骤种添加 make install
然后我们回到app工程,在app.pro最后添加 DESTDIR = $$OUT_PWD/../bin,在mainwindow.ui中添加一个垂直布局,在mainwindow.cpp里面添加加载插件的代码:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QPluginLoader>
#include <QFileInfo>
#include <QDir>
#include <QPushButton>
#include "appinterface.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
loadPlugins();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::loadPlugins()
{
QString pluginPath = QCoreApplication::applicationDirPath() + "/plugins";
QStringList filters;
#if defined(Q_OS_LINUX)
filters << "*.so";
#elif defined(Q_OS_WIN)
filters << "*.dll";
#endif
QFileInfoList plugins = QDir(pluginPath).entryInfoList(filters,
QDir::Files | QDir::NoSymLinks);
for (int i = 0; i < plugins.count(); ++i) {
QFileInfo plugin = plugins.at(i);
QPluginLoader *loader = new QPluginLoader(this);
loader->setFileName(plugin.absoluteFilePath());
bool result = loader->load();
qDebug() << QString("load plguin %1 result: ").arg(plugin.absoluteFilePath()) << result;
if (result) {
QObject *pluginInstance = loader->instance();
AppInterface *appInterface = qobject_cast<AppInterface *>(pluginInstance);
if (appInterface != nullptr) {
qDebug() << "add actions from plugin:" << appInterface->name();
QList<QAction *> actions = appInterface->actions();
for (int k = 0; k < actions.count(); ++k) {
QAction *ac = actions.at(k);
QPushButton *button = new QPushButton(ac->text(), this);
connect(button, &QPushButton::clicked, ac, &QAction::triggered);
ui->verticalLayout->addWidget(button);
}
}
} else {
qDebug() << loader->errorString();
}
}
}
最后构建运行,会出现类似的界面,界面上的2个按钮是通过插件返回的QAction来实现的。如果有多个插件就会加载多个插件,根据每个插件返回的QAction来创建相应的按钮。
总结
上面的示例只是一个很简单的例子,在真正的项目中,我们还需要做一些额外的工作来使得代码更加容易维护。比如我们需要创建PluginManager类来管理插件,IPlugin来实现插件的加载和卸载等工作。PluginManager的大致接口如下:
class IPlugin;
class PluginManager : public QObject
{
public:
PluginManager(QObject *parent = nullptr);
// 获取插件管理器全局的实例
static PluginManager *instance();
// 设置插件加载目录
void setPluginPath(const QString &path);
// 获取插件目录
void pluginPath() const;
// 加载所有插件
bool loadAll();
// 加载某一个插件
bool load(const QString &name);
// 卸载插件
bool unloadAll();
// 卸载某一个插件
bool unload(const QString &name);
// 查找
IPlugin *find(const QString &name);
private:
// 插件目录
QString m_pluginPath;
// 已加载的插件
QList<IPlugin *> m_plugins;
};
IPlugin的接口大致如下:
class IPlugin
{
public:
IPlugin();
virtual ~IPlugin();
// 插件名
virtual QString name() const = 0;
// 插件位置
virtual QString location() const = 0;
// 加载
virtual bool load() = 0;
// 卸载
virtual bool unload() = 0;
};
根据实际项目情况添加额外的接口或删除无用的接口。
在下一篇文章中通过Qt的源码来展示Qt实现插件的原理。感兴趣的朋友可以点一个关注。
在程序端
在程序端在程序端在程序端
在程序端在程序端