分为3个文件:
finddialog.h:
#ifndef FINDDIALOG_H #define FINDDIALOG_H #include < QDialog > class QCheckBox; class QLabel; class QLineEdit; class QPushButton; // 自定义类,继承于QDialog class FindDialog: public QDialog{ Q_OBJECT public : FindDialog(QWidget * parent = 0 ); // 构造函数 signals: void findNext( const QString & str, bool caseSensitive); void findPrev( const QString & str, bool caseSensitive); private slots: // 私有槽 void findClicked(); void enableFindButton( const QString & text); private : // 声明窗口要使用到的部件 QLabel * label; QLineEdit * lineEdit; QCheckBox * caseCheckBox; QCheckBox * backwardCheckBox; QPushButton * findButton; QPushButton * closeButton;}; #endif // FINDDIALOG_H
#include < QCheckBox > #include < QLabel > #include < QLayout > #include < QLineEdit > #include < QPushButton > #include " finddialog.h " FindDialog::FindDialog(QWidget * parent) :QDialog(parent) // 对父类进行构造 { label = new QLabel(tr( " Find &what: " ), this ); lineEdit = new QLineEdit( " wenhao " , this ); label -> setBuddy(lineEdit); // label,lineEdit是伙伴关系.按label的快捷键进入lineEdit中 caseCheckBox = new QCheckBox(tr( " Match &case " ), this ); backwardCheckBox = new QCheckBox(tr( " Search &backward " ), this ); findButton = new QPushButton(tr( " &Find " ), this ); findButton -> setDefault( true ); // 接回车键相当于按下findButton键 findButton -> setEnabled( false ); // 这个设置让其默认是不可以点击的. closeButton = new QPushButton(tr( " Close " ), this ); connect(lineEdit,SIGNAL(textChanged( const QString & )), this ,SLOT(enableFindButton( const QString & ))); connect(findButton,SIGNAL(clicked()), this ,SLOT(findClicked())); connect(closeButton,SIGNAL(clicked()), this ,SLOT(close())); QHBoxLayout * topLeftLayout = new QHBoxLayout; topLeftLayout -> addWidget(label); topLeftLayout -> addWidget(lineEdit); QVBoxLayout * leftLayout = new QVBoxLayout; leftLayout -> addLayout(topLeftLayout); leftLayout -> addWidget(caseCheckBox); leftLayout -> addWidget(backwardCheckBox); QVBoxLayout * rightLayout = new QVBoxLayout; rightLayout -> addWidget(findButton); rightLayout -> addWidget(closeButton); rightLayout -> addStretch( 1 ); // QHBoxLayout * mainLayout = new QHBoxLayout( this ); mainLayout -> setMargin( 11 ); mainLayout -> setSpacing( 4 ); mainLayout -> addLayout(leftLayout); mainLayout -> addLayout(rightLayout); setLayout(mainLayout); setWindowTitle(tr( " Find... " ));} void FindDialog::findClicked(){ QString text = lineEdit -> text(); bool caseSensitive = caseCheckBox -> isChecked(); if (backwardCheckBox -> isChecked()) emit findPrev(text,caseSensitive); else emit findNext(text,caseSensitive);} void FindDialog::enableFindButton( const QString & text){ findButton -> setEnabled( ! text.isEmpty());}
#include < QApplication > #include < QPushButton > #include < QHBoxLayout > #include < QWidget > #include " finddialog.h " int main( int argc, char * argv[]){ QApplication app(argc,argv); FindDialog * dialog = new FindDialog; dialog -> show(); return app.exec();}