ctk框架插件化开发实现功能的隔离,插件通信需要参照固定标准,这里介绍两种插件间通信的方法。(第三种是啥我也不知道……)还是以上章的MainWindow为例,主程序中以接口调用的方法弹出插件中的界面。由于涉及到Qt的Widget界面,请先将main函数中的QCoreApplication改为QApplication。
函数接口
上章我们已经编译出需要的动态库,首先确定我们需要插件向外部暴露的功能有什么,比如这里我们需要弹出窗口界面的操作,定义头文件如下:imainwindow.h
#ifndef IMAINWINDOW_H
#define IMAINWINDOW_H
#include <QObject>
class iMainWindow
{
public:
virtual void popMainWindow() = 0;
};
Q_DECLARE_INTERFACE(iMainWindow, "interface_mainwindow")
#endif // IMAINWINDOW_H
Q_DECLARE_INTERFACE将接口类向Qt系统申明,然后添加它的实现对象:
mainwindowplugin.h
#ifndef MAINWINDOWPLUGIN_H
#define MAINWINDOWPLUGIN_H
#include <QObject>
#include "../includes/imainwindow.h"
#include "ctkPluginContext.h"
#include "mainwindowdlg.h"
class MainWindowPlugin : public QObject, public iMainWindow
{
Q_OBJECT
Q_INTERFACES(iMainWindow)
public:
MainWindowPlugin(ctkPluginContext *context);
virtual void popMainWindow();
private:
ctkPluginContext *m_context;
MainWindowDlg* m_windowDlg;
};
#endif // MAINWINDOWPLUGIN_H
mainwindowplugin.cpp
#include "mainwindowplugin.h"
MainWindowPlugin::MainWindowPlugin(ctkPluginContext *context)
:m_context(context)
{
m_windowDlg = new MainWindowDlg;
}
void MainWindowPlugin::popMainWindow()
{
m_windowDlg->show();
}
这仍是Qt的插件定义格式,但是不会作为插件导出,外部功能接口可以自定义。
服务注册
功能节接口完成后,在插件启动时注册到ctk框架的服务中,代码如下:mainwindowactivator.cpp
void MainWindowActivator::start(ctkPluginContext *context)
{
qDebug() << "mainwindow start";
m_plugin = new MainWindowPlugin(context);
ctkDictionary dic;
context->registerService<iMainWindow>(m_plugin, dic);
}
接口调用
主函数框架及插件加载完成后,即可调用插件接口,代码如下:main.cpp
#include "../includes/imainwindow.h"
……
ctkPluginContext* context = framework->getPluginContext();
ctkServiceReference ref =context->getServiceReference<iMainWindow>();
iMainWindow* mainWindow;
if(ref)
mainWindow = context->getService<iMainWindow>(ref);
if(mainWindow)
mainWindow->popMainWindow();