前一章已經實現了主程序調用加載插件功能,這一章描述主程序和插件間通信功能
說道Qt的通信必須要了解信號和槽的機制原理,這里不做論述,不清楚的同學去看看信號和槽機制
不廢話直接上步驟,在上一章的基礎下進行修改
第一步:在插件中定義一個接收槽
#include "mainwidget.h" #include "ui_mainwidget.h" #include "qtimer.h" #include "qdatetime.h" mainwidget::mainwidget(QWidget *parent) : QWidget(parent), ui(new Ui::mainwidget) { ui->setupUi(this); timer = new QTimer(this); //新建定時器 connect(timer,SIGNAL(timeout()),this,SLOT(timerUpDate())); //關聯定時器計滿信號和相應的槽函數 timer->start(1000); } mainwidget::~mainwidget() { delete ui; } 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); } void mainwidget::time_start() { timer->start(); ui->label->setText("start"); } void mainwidget::time_stop() { timer->stop(); ui->label->setText("stop"); }
第二步 生成插件
這一步和上一章內容不變,替換要實現的插件的內容即可
點擊運行生成插件,找到插件testpluginplugin.dll
復制粘貼到主程序的程序運行目錄下
第三步 主程序加載插件並設置信號槽
connect(ui->action,SIGNAL(triggered()), testwidget,SLOT(time_start())); connect(ui->action_2,SIGNAL(triggered()),testwidget,SLOT(time_stop()));
效果圖:
1)加載插件成功后默認時間是不斷刷新
2)點擊停止后時間顯示stop
3)點擊開始,時間繼續刷新
這里就完成了主界面操作插件的功能
源碼下載http://download.csdn.net/detail/huangyuancao/6654197