您的位置:首页 > 编程语言 > Qt开发

Qt4.8.6插件化编程例程--仅供参考

2015-07-28 15:59 507 查看
工程结构:



工程源码:

-------------PluginAnimal.pro------------

TEMPLATE = subdirs

SUBDIRS += \
dog \
animal


-------------animal.pro------------------
#-------------------------------------------------
#
# Project created by QtCreator 2015-07-28T14:45:07
#
#-------------------------------------------------

QT       += core

QT       -= gui

DESTDIR = ../../PluginAnimal/exe

TARGET = animal
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

HEADERS += \
animalinterface.h


-----------------animalinterface.h--------------------

#ifndef ANIMALINTERFACE_H
#define ANIMALINTERFACE_H

#include <QString>
#include <QtPlugin>

class AnimalInterface
{
public:
virtual QString type()=0;
virtual int age()=0;
virtual void voice()=0;
};

#define AnimalInterface_iid    "org.qt-proj.Qt.Animal"

Q_DECLARE_INTERFACE(AnimalInterface, AnimalInterface_iid)

#endif // ANIMALINTERFACE_H


--------------main.cpp---------------
#include <QCoreApplication>
#include "animalinterface.h"
#include <QDebug>
#include <QPluginLoader>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

qDebug()<<"animal ...";

QPluginLoader loader(QCoreApplication::applicationDirPath().append("/dog.dll"));
QObject *obj=qobject_cast<QObject *>(loader.instance());

if(obj){
qDebug()<<"load success!";
AnimalInterface *animal=qobject_cast<AnimalInterface *>(obj);
if(animal){
qDebug()<<"type:"<<animal->type()<<", age:"<<animal->age();
animal->voice();
}else{
qDebug()<<"animal error!";
}
}else{
qDebug()<<"object error!";
}

return 0;
}


------------dog.pro-----------

#-------------------------------------------------
#
# Project created by QtCreator 2015-07-28T14:47:04
#
#-------------------------------------------------

QT       -= gui

TARGET = dog
TEMPLATE = lib

DESTDIR = ../../PluginAnimal/exe

SOURCES += dog.cpp

HEADERS += dog.h

unix {
target.path = /usr/lib
INSTALLS += target
}


--------------dog.h---------------
#ifndef DOG_H
#define DOG_H

#include "../animal/animalinterface.h"

class Dog : public QObject, AnimalInterface
{
Q_OBJECT
Q_INTERFACES(AnimalInterface)
public:
QString type();
int age();
void voice();
};

#endif // DOG_H


---------------dog.cpp--------------
#include "dog.h"
#include <QDebug>

QString Dog::type()
{
return "dog";
}

int Dog::age()
{
return 9;
}

void Dog::voice()
{
qDebug()<<"dog bark!";
}

Q_EXPORT_PLUGIN2(AnimalInterface_iid, Dog)


运行效果:



(-----------完----------)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: