头文件:
#ifndef FINDDIALOG_H
#define FINDDIALOG_H
#include <QDialog>
#include <QHBoxLayout>
#include <QCheckBox>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
class FindDialog : public QDialog
{
Q_OBJECT
//对于所有定义了信号和槽的类,在类定义开始处的Q_OBJECT宏都是必
需的
public:
FindDialog(QWidget *parent = 0);
//典型的QT窗口部件类的定义方式,parent参数指定了它的父窗口部件
,该参数的默认值是一个空指针,意味着该对话框没有父对象
signals:
void findNext(const QString &str,Qt::CaseSensitivity cs);
void findPrevious(const QString &str,Qt::CaseSensitivity cs);
//声明了当用户单击Find按钮时对话框发出的两个信号
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 <QtGui>
#include "finddialog.h"
FindDialog::FindDialog(QWidget *parent)
:QDialog(parent)//把parent参数传给了基类的构造函数
{
label = new QLabel(tr("Find &what:"));
lineEdit = new QLineEdit;
label->setBuddy(lineEdit);
//设置行编辑器为标签的伙伴,当用户按下标签的快捷键时,焦点会移动
到这个行编辑器(该标签的伙伴)上。
caseCheckBox = new QCheckBox(tr("Match &case"));
backwardCheckBox = new QCheckBox(tr("Search &backward"));
findButton = new QPushButton(tr("&Find"));
findButton->setDefault(true);
//让Find按钮成为此对话框的默认按钮,即当用户按下回车时能默认按
下的按钮
findButton->setEnabled(false);
//设置Find按钮在初始时是禁用的
closeButton = new QPushButton(tr("Close"));
connect(lineEdit,SIGNAL(textChanged(const QString &)),
this,SLOT(enableFindButton(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();
//最后加了一个伸展器,用它来占据Find按钮和Close按钮所余下的空
白区域,这样可以确保这些按钮完全占用它们所在布局的**上部空间
**。如果不加的话,默认**上下居中分布**
QHBoxLayout *mainLayout = new QHBoxLayout;
mainLayout->addLayout(leftLayout);
mainLayout->addLayout(rightLayout);
setLayout(mainLayout);
setWindowTitle(tr("Find"));
//设置固定高度,sizeHint()合适的.height()高度
}
void FindDialog::findClicked()
{
QString text =lineEdit->text();
Qt::CaseSensitivity cs =
caseCheckBox->isChecked()?Qt::CaseSensitive:Qt::CaseInsensitive;
if(backwardCheckBox->isChecked())
{
emit findPrevious(text,cs);
}else
{
emit findNext(text,cs);
}
//用户按下Find按钮时,就会调用findClicked()槽,而该槽会根据
Search backward选项的取值发射(emit)findPrevious()或
findNext()信号
}
void FindDialog::enableFindButton(const QString &text)
{
findButton->setEnabled(!text.isEmpty());
//当行编辑器中内容发生改变且内容不为空时,激活Find按钮
}
运行示例
- tr()函数调用是把字符串翻译成其他语言的标记
- “与”操作符“&”快捷键,Find &what创建了一个Find按钮,用户可以在那些支持快捷键的平台下通过按下 ALT + F 快捷键来激活它在实际界面中按下ALT键时,若按钮上有带下划线的字母表示有快捷键 ALT+ 字母
- Qt在删除FindDialog(父对象)时,自动删除其所属的所有子对象