基于Qt插件机制扩展应用程序示例

什么是插件

插件(Plug-in,又称addin、add-in、addon或add-on,又译外挂)是一种遵循一定规范的应用程序接口编写出来的程序。其只能运行在程序规定的系统平台下(可能同时支持多个平台),而不能脱离指定的平台单独运行。因为插件需要调用原纯净系统提供的函数库或者数据。很多软件都有插件,插件有无数种。例如在IE中,安装相关的插件后,WEB浏览器能够直接调用插件程序,用于处理特定类型的文件。以上是百度百科中的对插件的描述

创建Qt创建

Qt 提供了2种APIs来创建插件:

  1. 一种高级API,用于为Qt本身编写插件:自定义数据库驱动程序,图像格式,文本编解码器,自定义样式等。
  2. 一种用于扩展Qt应用程序的低级API。也就是说扩展我们自己使用Qt编写的程序。这要求应用程序使用 QPluginLoader 检测和加载插件。在这种情况下,插件可以提供任意功能,不限于数据库驱动程序、图像格式、文本编解码器、样式以及扩展Qt功能的其他类型的插件。

例如,如果你想编写一个自定义的QStyle子类,并让Qt应用程序动态加载它,你可以使用第一种方式。

该文章主要通过示例来展示第二种方式创建插件。通过插件扩展应用程序可涉及以下步骤:

在程序端:

  1. 定义一组接口(只有纯虚函数的类)。
  2. 使用Q_DECLARE_INTERFACE()宏告诉Qt的元对象系统有关接口的信息。
  3. 在程序中使用 QPluginLoader加载插件。
  4. 使用qobject_cast()测试插件是否实现给定的接口。

在插件端:

  1. 声明一个插件类,该类继承自QObject和插件要提供的接口类。
  2. 使用Q_INTERFACES()宏告诉Qt的元对象系统有关接口的信息。
  3. 使用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实现插件的原理。感兴趣的朋友可以点一个关注。

示例代码:PluginDemo: Qt 插件使用示例

在程序端

在程序端在程序端在程序端

在程序端在程序端

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小王哥编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值