#ifndef QPLUGIN_SYSTEM_H
#define QPLUGIN_SYSTEM_H
#include <QObject>
#include <QVector>
#include <QPluginLoader>
#include <QDir>
template<class T>
class QPluginSystem
{
public:
void setup();
int getAddonCnt(){return addons.size();}
T* getAddonByIndex(int index){return addons.at(index);}
private:
QVector<QPluginLoader*> loaders;
QVector<T*> addons;
};
template<class T>
void QPluginSystem<T>::setup()
{
QString path = QDir::currentPath();
path += QDir::separator();
path += "addons";
QDir pluginsDir(path);
foreach(QString fileName,pluginsDir.entryList(QDir::Files))
{
bool autodel = false;
QPluginLoader* pluginLoader = new QPluginLoader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = pluginLoader->instance();
if(plugin)
{
T *interface = qobject_cast<T*>(plugin);
if(interface)
{
addons.push_back(interface);
loaders.push_back(pluginLoader);
autodel = true;
}
}
if(autodel == false)
delete pluginLoader;
}
}
#endif
其中T是插件对象,需要继承QObject
另外虽然我没试过,但是我感觉增加QPluginLoader链表是很有必要的