Qt一步一步实现插件调用(附源码)

最近手里几个项目都采用插件的方式进行开发工作,这里记录一下实现方法,给需要的同学一个参考,

在linux系统和window系统都能成功编译通过,不废话直接步骤

第一步:建立插件原型

新建一个Qt项目,实现一个一个实时刷新当前时间这这么一个功能,工程命名为testdemo

如图

效果图 

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mainwidget::mainwidget(QWidget *parent) :
     QWidget(parent),
     ui( new  Ui::mainwidget)
{
     ui->setupUi( this );
     QTimer *timer =  new  QTimer( this );
     //新建定时器
     connect(timer,SIGNAL(timeout()), this ,SLOT(timerUpDate()));
     //关联定时器计满信号和相应的槽函数
     timer->start(1000);
}
void  mainwidget::timerUpDate()
{
     QDateTime  time  = QDateTime::currentDateTime(); //获取系统现在的时间
     QString str =  time .toString( "yyyy-MM-dd hh:mm:ss ddd" );  //设置显示格式
     QString strr= strr.fromLocal8Bit( "当前时间:" )+str; //调用中文显示
     ui->label->setText(strr);
}

第二步:生成插件文件

window下一般是dll后缀,linux下一般是so后缀

这里需要细说下直接上操作图片

1)这里选择Other Project 里面Qt Custom Designer Widget, 工程命名为testplugin

2)把第一步插件模型的文件附加到这个生成插件的工程中

3)找到testpluginPlugin.cpp文件下修改

1
2
3
4
5
QWidget*testpluginPlugin::createWidget(QWidget*parent)
{
//returnnewtestplugin(parent);//原来代码
returnnewmainwidget(parent); //修改后代码
}

效果图

在生成目录下就能找到生成的插件testpluginplugin.dll。

第三步 主程序调用插件

同样的新建一个主程序工程,命名为testmain

效果图

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//加载插件函数
QWidget *loadPlugins(QString pluginFileName, QWidget *parent)
{
     QPluginLoader loader( pluginFileName );
 
     bool  b = loader.load();
     if (b)
         qDebug( "loder ok!\r\n" );
     else
         qDebug( "loder error!\r\n" );
 
     QObject *plugin = loader.instance();
     if  (plugin)
     {
         QDesignerCustomWidgetInterface *iCustomWidgetInterface = qobject_cast<QDesignerCustomWidgetInterface *>(plugin);
         if ( iCustomWidgetInterface ){
             QWidget *widget = iCustomWidgetInterface->createWidget( parent );
             return  widget;
         }
     }
     else
         qDebug( "loader.instance() error\r\n" );
 
     return  NULL;
}
//初始化插件
void  MainWindow::loadplugin()
{
     QString DirPath=QApplication::applicationDirPath();
     DirPath=DirPath.left(DirPath.lastIndexOf( "/" ));
     QString pluginfilename;
     pluginfilename = DirPath+ "/testpluginplugin.dll" ;
     testwidget = loadPlugins( pluginfilename,  this  );
}

这样一个完整的插件系统就实现了。

源码下载链接http://download.csdn.net/detail/huangyuancao/6653667



FROM: http://www.cnblogs.com/newstart/p/3456918.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值