最近手裏幾個項目都採用插件的方式進行開發工做,這裏記錄一下實現方法,給須要的同窗一個參考,linux
在linux系統和window系統都能成功編譯經過,不廢話直接步驟app
第一步:創建插件原型函數
新建一個Qt項目,實現一個一個實時刷新當前時間這這麼一個功能,工程命名爲testdemoui
如圖this
效果圖 spa
代碼.net
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後綴blog
這裏須要細說下直接上操做圖片圖片
1)這裏選擇Other Project 裏面Qt Custom Designer Widget, 工程命名爲testplugin
2)把第一步插件模型的文件附加到這個生成插件的工程中
3)找到testpluginPlugin.cpp文件下修改
QWidget*testpluginPlugin::createWidget(QWidget*parent) { //returnnewtestplugin(parent);//原來代碼 returnnewmainwidget(parent);//修改後代碼 }
效果圖
在生成目錄下就能找到生成的插件testpluginplugin.dll。
第三步 主程序調用插件
一樣的新建一個主程序工程,命名爲testmain
效果圖
代碼
//加載插件函數 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 ); }
這樣一個完整的插件系統就實現了。