Generation and use of qt plug-in Plugin

Keywords: Qt JSON

Sketch

Sometimes, when we are making an application, we don't want the software we generate to be just an EXE file, but to split it into modules, the finer the better. In the future, it is very convenient to release updates. We only update a small part of them, not the whole application. (let's look at the code.)

Plug-in generation

//Let's first define an interface header file, plugindemoplugin.h
QT_BEGIN_NAMESPACE
class QtPluginDemoInterface
{
public:
    virtual ~QtPluginDemoInterface() {}
    //Interface to declare a print function
    virtual void printMessage(const QString& message) = 0;
};

#define QDesignerCustomWidgetInterface_iid "org.qt-project.QtPluginDemoInterface"
Q_DECLARE_INTERFACE(QtPluginDemoInterface, QDesignerCustomWidgetInterface_iid)

QT_END_NAMESPACE
//Derived class header file 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:
    void printMessage(const QString& message) override;
};
//plugindemo.cpp
//In defining a derived class to implement the interface in our base class, compile and generate the library file
void pluginDemo::printMessage(const QString& message)
{
    //Implementing print function in derived class
    qDebug() << "---------------This is QtPluginDemoInterface Demo Test--------------" << message;
}

Next, we load the plug-in in our UI main program

//plugintest.h
#include <QtWidgets/QMainWindow>
#include "ui_plugintest.h"

class QtPluginDemoInterface;
class PluginTest : public QMainWindow
{
    Q_OBJECT

public:
    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());
    //Here I create a new plugins folder, and put the dll file generated above into this folder
    pluginsDir.cd("plugins");
    //Load the library file under the current folder
    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)
                return true;
        }
    }

    return false;
}

Design sketch

Posted by tarleton on Sun, 12 Apr 2020 08:55:32 -0700