#define FINDDIALOG_H
#include <QtGui/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 // FINDDIALOG_H
#include <QtGui>
#include "finddialog.h"
FindDialog::FindDialog(QWidget *parent):QDialog(parent)
{
label = new QLabel(tr("Find &what:"));
lineEdit = new QLineEdit;
label->setBuddy(lineEdit);
caseCheckBox = new QCheckBox(tr("Match &case"));
backwardCheckBox = new QCheckBox(tr("Search &backford"));
findButton = new QPushButton(tr("&Find"));
findButton->setDefault(true);
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()
{
QString text = lineEdit->text();
Qt::CaseSensitivity cs = caseCheckBox->isChecked()?Qt::CaseInsensitive : Qt::CaseInsensitive;//判断checkbox是不是被选中,暂时不是很了解,据说是用于大小写敏感的查找
if(backwardCheckBox->isChecked()) {
emit findPrevious(text, cs);
} else {
emit findNext(text, cs);
}
}
void FindDialog::enableFindButton(const QString &text)
{
findButton->setEnabled(!text.isEmpty());
}
#include <QApplication>
#include "finddialog.h"
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
FindDialog *dialog = new FindDialog;
dialog->show();
return app.exec();
}
(1)tr()函数。被它处理的字符串可以使用工具提取出来翻译成其他语言,也就是做国际化使用。
(2)findButton = new QPushButton(tr("&Find"));&代表快捷键。当按下Alt+f的时候就相当于被点击。
(3)setBuddy()函数。当按下Alt+w时候,会选中QLineEdit控件里面的内容。
(4)共有4个布局,分别时左上布局,左边布局,右边布局,总布局。把2个组件以水平布局的方式放入到左上布局之中,然后把左上布局,和2个组件以垂直布局的方式放入到左边布局,以垂直布局的方式把2个组件放入到右边布局,最后以水平布局的方式把左边布局和右边布局放入到总布局当中。说明布局可以嵌套。
(5)FindDialog::FindDialog(QWidget *parent):QDialog(parent)初始化父类,相当于new QPutton(0,“hello”)之类的。