你在看這篇文章的時候,需要對C++有一定的瞭解。
首先我們用QT建立一個空的qt4項目,然後添加標頭檔MessageButDlg.h
內容如下:
#ifndef MESSAGEBUTDLG_H<br />#define MESSAGEBUTDLG_H</p><p>#include<QDialog><br />#include<QLabel><br />#include<QPushButton><br />#include<QGridLayout></p><p>//定義一個繼承於QDialog的類<br />class MessageButDlg:public QDialog<br />{<br /> Q_OBJECT<br />public:<br /> MessageButDlg(QWidget *parent=0,Qt::WindowFlags f=0);<br /> ~MessageButDlg();<br />public:<br /> QGridLayout *layout;<br /> QLabel *label;<br /> QPushButton *QuestionButton;<br /> QPushButton *WarningButton;<br />private slots:<br /> void slotQuestionBut();<br /> void slotWarningBut();<br />};</p><p>#endif // MESSAGEBUTDLG_H<br />
然後我們添加一個MessageButDlg.cpp的實現檔案,實現標頭檔中定義的變數與函數。
內容如下:
#include"MessageButDlg.h"<br />#include<QMessageBox></p><p>MessageButDlg::MessageButDlg(QWidget *parent, Qt::WindowFlags f)<br /> :QDialog(parent,f)<br />{<br /> setWindowTitle(tr("MessageButton Test"));<br /> layout = new QGridLayout(this);</p><p> //定義申明控制項<br /> label = new QLabel;<br /> label->setText(tr("This is text Label"));<br /> QuestionButton = new QPushButton;<br /> QuestionButton->setText(tr("QuestionButton"));</p><p> WarningButton = new QPushButton;<br /> WarningButton->setText(tr("WarningButton"));</p><p> //添加控制項布局<br /> layout->addWidget(label,0,0);<br /> layout->addWidget(QuestionButton,1,0);<br /> layout->addWidget(WarningButton,1,1);</p><p> //進行訊號需槽串連<br /> connect(QuestionButton,SIGNAL(clicked()),this,SLOT(slotQuestionBut()));<br /> connect(WarningButton,SIGNAL(clicked()),this,SLOT(slotWarningBut()));</p><p>}</p><p>//定義訊號槽進行的操作函數<br />void MessageButDlg::slotQuestionBut()<br />{<br /> switch(QMessageBox::question(this,"Question",<br /> tr("It's end of document,search for begin?"),<br /> QMessageBox::Ok|QMessageBox::Cancel,QMessageBox::Ok))<br /> {<br /> case QMessageBox::Ok:<br /> label->setText("Question Button / OK");<br /> break;<br /> case QMessageBox::Cancel:<br /> label->setText("Question Button / Cancel");<br /> break;<br /> default:<br /> break;<br /> }<br /> return;<br />}</p><p>//定義訊號槽進行操作的函數<br />void MessageButDlg::slotWarningBut()<br />{<br /> switch(QMessageBox::warning(this,"Warning",<br /> tr("It's error."),<br /> QMessageBox::Ignore|QMessageBox::Abort,<br /> QMessageBox::Ignore))<br /> {<br /> case QMessageBox::Ignore:<br /> label->setText("Warning Button /Ignore");<br /> break;<br /> case QMessageBox::Abort:<br /> label->setText("Warning Button /Abort");<br /> break;<br /> default:<br /> break;<br /> }<br /> return;<br />}</p><p>MessageButDlg::~MessageButDlg()<br />{</p><p>}
上面兩步完成後,我們只需要添加一個main.cpp檔案,在裡面調用我們上面的定義的類就可以了。
main.cpp內容如下:
#include"MessageButDlg.h"<br />#include<QApplication></p><p>int main(int argc,char *argv[])<br />{<br /> QApplication app(argc,argv);<br /> //通過我們定義的類定義一個變數w;<br /> MessageButDlg w;<br /> //通過調用w繼承的QDialog的show()屬性顯示視窗。<br /> w.show();<br /> return app.exec();<br />}<br />
好了,到這裡整個測試程式就完成了,然後我們按f5或ctrl+r就可以運行程式了。
只要稍等一下就可以看到一個QT編寫出的視窗程序了。