首先新建一个工程,Qt Gui Application,然后最后一步注意,Base Dialog选择QDialog,而不是默认的QMainWindow
头文件
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
class QCheckBox;
class QLabel;
class QLineEdit;
class QPushButton;
class FindDialog : public QDialog
{
Q_OBJECT
public:
FindDialog(QWidget *parent = 0);
~FindDialog();
signals:
void findNext(const QString &str, Qt::CaseSensitivity cs);
void findPrevious(const QString &str, Qt::CaseSensitivity cs);
private slots:
void findClicked();
void enableFindButton(const QString &text);
private:
QLabel *label;
QLineEdit *lineEdit;
QCheckBox *caseCheckBox;
QCheckBox *backwardCheckBox;
QPushButton *findButton;
QPushButton *closeButton;
};
#endif // DIALOG_H
源文件:
#include "dialog.h"
#include <QCheckBox>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QHBoxLayout>
FindDialog::FindDialog(QWidget *parent)
: QDialog(parent)
{
//&字母相当于定义个快捷键,当你按下Alt+F的时候,这个按钮就相当于被点击
label = new QLabel(tr("Find &what:"));
lineEdit = new QLineEdit;
//这个label使用了setBuddy函数,它的意思是,当label获得焦点时,
//比如按下Alt+W,它的焦点会自动传给它的buddy,也就是lineEdit
label->setBuddy(lineEdit);
caseCheckBox = new QCheckBox(tr("Match &case"));
backwardCheckBox = new QCheckBox(tr("Search &backford"));
findButton = new QPushButton(tr("&Find"));
findButton->setEnabled(false);//初始禁用
closeButton = new QPushButton(tr("Close"));
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();
//将左半部分和右半部分整体加入水平布局
QHBoxLayout *mainLayout = new QHBoxLayout;
mainLayout->addLayout(leftLayout);
mainLayout->addLayout(rightLayout);
setLayout(mainLayout);
//对话框的标题
setWindowTitle(tr("Find"));
setFixedHeight(sizeHint().height());
}
FindDialog::~FindDialog()
{
}
void FindDialog::findClicked()
{
//首先取出lineEdit的输入值
QString text = lineEdit->text();
//然后判断caseCheckBox是不是选中,如果选中就返回Qt::CaseInsensitive,否则返回Qt::CaseSensitive
Qt::CaseSensitivity cs = caseCheckBox->isChecked() ? Qt::CaseInsensitive : Qt::CaseSensitive;
//查找方向分支
if(backwardCheckBox->isChecked()) {
emit findPrevious(text, cs);
} else {
emit findNext(text, cs);
}
}
void FindDialog::enableFindButton(const QString &text)
{
//当文本不为空时启用Find按钮
findButton->setEnabled(!text.isEmpty());
}
解释见注释。
下面是main函数,这部分工程自动生成:
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
FindDialog w;
w.show();
return a.exec();
}