@1405010312
2017-06-05T07:52:40.000000Z
字数 2327
阅读 472
C++GUIQt4
- 这一章讲解如何使用Qt创建对话框.对话框为用户提供了许多选项和多种选择,允许用户把选项设置为他们喜欢的变量值并从中做出选择.本章将首先完全用手写代码的方式创建第一个对话框,以便能够说明是如何完成这项工程的.然后将使用Qt的可视化界面设计工具Qt设计师.使用Qt设计师比手写代码要快得多,并且可以使不通的设计测试工作以及稍后对设计的修改工作变得异常轻松.
完全使用C++编写的一个Find对话框,将实现一个拥有自主权的对话框.通过这一过程,就可以让对话框拥有自己的信号和槽,成为一个独立的,完备的控件.
finddialog.h
#ifndef FINDDIALOG_H
#define FINDDIALOG_H
#include <QDialog>
class QCheckBox;
class QLabel;
class QLineEdit;
class QPushButton>
class FindDialog: public QDialog{
Q_OBJECT
public:
FindDialog(QWidget *parent=0);
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.cpp
#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 &backward"));
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(closeButtonm 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());
}
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);
}
}