QT的对话框类QDialog实现了对话框的基础,它从QWidget继承,可以提供一个返回值。
创建一个对话框的步骤如下:
- 创建一个从QDialog继承的类。
- 添加对话框中的部件,如按钮等等
- 创建各种需要的消息和槽。
01 |
class FindDialog : public QDialog |
05 |
FindDialog(QWidget *parent = 0); |
07 |
void findNext( const QString &str,Qt::CaseSensitivity cs); |
08 |
void findPrevious( const QString &str,Qt::CaseSensitivity cs); |
11 |
void enableFindButton( const QString &text); |
15 |
QCheckBox *caseCheckBox; |
16 |
QCheckBox *backwardCheckBox; |
17 |
QPushButton *findButton; |
18 |
QPushButton *closeButton; |
这样一个对话框子类就建立好了,那么该实现了。
首先是在构造函数中创建对话框中的部件并设置,并且设计好部件在窗体中的布局。
01 |
FindDialog::FindDialog(QWidget *parent) |
04 |
label = new QLabel(tr( "Find &What:" )); |
05 |
lineEdit = new QLineEdit; |
07 |
label->setBuddy(lineEdit); |
08 |
caseCheckBox = new QCheckBox; |
09 |
findButton = new QPushButton(tr( "&Find" )); |
10 |
findButton->setDefault( true ); |
11 |
findButton->setEnabled( false ); |
12 |
closeButton = new QPushButton(tr( "Close" )); |
14 |
connect(lineEdit,SIGNAL(textChanged( const QString &)), |
15 |
this ,SLOT(enableFindButton( const QString & ))); |
17 |
connect(findButton,SIGNAL(clicked()), this ,SLOT(findClicked())); |
19 |
connect(closeButton,SIGNAL(clicked()), this ,SLOT(close())); |
21 |
QHBoxLayout *topLeftLayout = new QHBoxLayout; |
22 |
topLeftLayout->addWidget(label); |
23 |
topLeftLayout->addWidget(lineEdit); |
24 |
QVBoxLayout *leftLayout = new QVBoxLayout; |
25 |
leftLayout->addLayout(topLeftLayout); |
26 |
leftLayout->addWidget(caseCheckBox); |
27 |
leftLayout->addWidget(backwardCheckBox); |
28 |
QVBoxLayout *rightLayout = new QVBoxLayout; |
29 |
rightLayout->addWidget(findButton); |
30 |
rightLayout->addWidget(closeButton); |
31 |
rightLayout->addStretch(); |
33 |
QHBoxLayout *mainLayout = new QHBoxLayout; |
34 |
mainLayout->addLayout(leftLayout); |
35 |
mainLayout->addLayout(rightLayout); |
36 |
setLayout(mainLayout); |
37 |
setWindowTitle(tr( "Find" )); |
38 |
setFixedHeight(sizeHint().height()); |
接着实现对话框中所用到的槽
01 |
void FindDialog::findClicked() |
03 |
QString text = lineEdit->text(); |
05 |
Qt::CaseSensitivity cs = caseCheckBox->isChecked() ? |
06 |
Qt::CaseSensitive : Qt::CaseInsensitive; |
08 |
if (backwardCheckBox->isChecked()) |
10 |
emit findPrevious(text,cs); |
14 |
emit findNext(text,cs); |
18 |
void FindDialog::enableFindButton( const QString &text) |
20 |
findButton->setEnabled(!text.isEmpty()); |
01 |
#include <QApplication> |
02 |
#include <finddialog.h> |
04 |
int main( int argc, char *argv[]) |
06 |
QApplication app(argc,argv); |
07 |
FindDialog *dialog = new FindDialog; |
运行如图:
创建对话框的大致步骤就如上面的了。当然也可以通过QT Designer进行可视化的设计对话框后给程序调用。
关于lineEdit:
lineEdit的输入可以通过检验器件来控制输入。如:QIntValidator,QDoubleValidator,QRegExpValidator。
示例:
1 |
QRegExp regExp( "[A-Za-z][1-9][0-9]{0,2}" ); |
2 |
lineEdit->setValidator( new QRegExpValidator(regExp, this )); |
这里限定lineEdit输入的第一个字符必须是字母,第二个字符必须是1-9的数字,然后可一个输入0至2个0到9的数字。
感觉这里正则真的很方便哦。以前写代码的时候控制edit数据总会写一堆代码,而QT这里2距代码搞定。。。。