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

工程结构:


工程源码:

-------------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)

运行效果:


(-----------完----------)







  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值