[关闭]
@1405010312 2017-06-05T07:52:40.000000Z 字数 2327 阅读 472

第二章 创建对话框

C++GUIQt4



1.1 大纲

  • 这一章讲解如何使用Qt创建对话框.对话框为用户提供了许多选项和多种选择,允许用户把选项设置为他们喜欢的变量值并从中做出选择.本章将首先完全用手写代码的方式创建第一个对话框,以便能够说明是如何完成这项工程的.然后将使用Qt的可视化界面设计工具Qt设计师.使用Qt设计师比手写代码要快得多,并且可以使不通的设计测试工作以及稍后对设计的修改工作变得异常轻松.

1.2 子类化QDialog

1.2.1 第一个例子

完全使用C++编写的一个Find对话框,将实现一个拥有自主权的对话框.通过这一过程,就可以让对话框拥有自己的信号和槽,成为一个独立的,完备的控件.
finddialog.h

  1. #ifndef FINDDIALOG_H
  2. #define FINDDIALOG_H
  3. #include <QDialog>
  4. class QCheckBox;
  5. class QLabel;
  6. class QLineEdit;
  7. class QPushButton>
  8. class FindDialog: public QDialog{
  9. Q_OBJECT
  10. public:
  11. FindDialog(QWidget *parent=0);
  12. signals:
  13. void findNext(const QString &str, Qt::CaseSensitivity cs);
  14. void findPrevious(const QString &str, Qt::CaseSensitivity cs);
  15. private slots:
  16. void findClicked();
  17. void enableFindButton(const QString &text);
  18. private:
  19. QLabel *label;
  20. QLineEdit *lineEdit;
  21. QCheckBox *caseCheckBox;
  22. QCheckBox *backwardCheckBox;
  23. QPushButton *findButton;
  24. QPushButton *closeButton;
  25. };
  26. #endif

finddialog.cpp

  1. #include <QtGui>
  2. #include "finddialog.h"
  3. FindDialog::FindDialog(QWidget *parent)
  4. :QDialog(parent){
  5. label = new QLabel(tr("Find &what:"));
  6. lineEdit = new QLineEdit;
  7. label->setBuddy(lineEdit);
  8. caseCheckBox = new QCheckBox(tr("Match &case"));
  9. backwardCheckBox = new QCheckBox(tr("Search &backward"));
  10. findButton = new QPushButton(tr("&Find"));
  11. findButton->setDefault(true);
  12. findButton->setEnabled(false);
  13. closeButton = new QPushButton(tr("Close"));
  14. connect(lineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(enableFindButton(const QString &)));
  15. connect(findButton, SIGNAL(clicked()), this, SLOT(findClicked()));
  16. connect(closeButtonm SIGNAL(clicked()), this, SLOT(close()));
  17. QHBoxLayout *topLeftLayout = new QHBoxLayout;
  18. topLeftLayout->addWidget(label);
  19. topLeftLayout->addWidget(lineEdit);
  20. QVBoxLayout *leftLayout = new QVBoxLayout;
  21. leftLayout->addLayout(topLeftLayout);
  22. leftLayout->addWidget(caseCheckBox);
  23. leftLayout->addWidget(backwardCheckBox);
  24. QVBoxLayout *rightLayout = new QVBoxLayout;
  25. rightLayout->addWidget(findButton);
  26. rightLayout->addWidget(closeButton);
  27. rightLayout->addStretch();
  28. QHBoxLayout *mainLayout = new QHBoxLayout;
  29. mainLayout->addLayout(leftLayout);
  30. mainLayout->addLayout(rightLayout);
  31. setLayout(mainLayout);
  32. setWindowTitle(tr("Find"));
  33. setFixedHeight(sizeHint().height());
  34. }
  35. void FindDialog::findClicked(){
  36. QString text = lineEdit->text();
  37. Qt::CaseSensitivity cs = caseCheckBox->isChecked()?Qt::CaseSensitive:Qt::CaseInsensitive;
  38. if(backwardCheckBox->isChecked()){
  39. emit findPrevious(text, cs);
  40. }else{
  41. emit findNext(text, cs);
  42. }
  43. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注