Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1390624
  • 博文数量: 120
  • 博客积分: 182
  • 博客等级: 入伍新兵
  • 技术积分: 2278
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-19 16:31
文章分类

全部博文(120)

文章存档

2015年(12)

2014年(13)

2013年(40)

2012年(55)

分类: Windows平台

2013-10-14 09:34:20

之前的一篇<>(http://blog.chinaunix.net/uid-27177626-id-3940399.html)是在Qt设计器中事先设计好界面布局,然后 通过触发按钮事件完成计算圆的面积的功能,这篇则完全通过代码来实现界面的布局设计和功能的实现。

点击(此处)折叠或打开

  1. //dialog.h
  2. #ifndef DIALOG_H
  3. #define DIALOG_H

  4. #include <QDialog>

  5. class QLabel;
  6. class QLineEdit;

  7. namespace Ui {
  8. class Dialog;
  9. }

  10. class Dialog : public QDialog
  11. {
  12.     Q_OBJECT

  13. public:
  14.     explicit Dialog(QWidget *parent = 0);
  15.     ~Dialog();

  16. private slots:
  17.     void showArea();

  18. private:
  19.     Ui::Dialog *ui;
  20.     QLabel *label1, *label2;
  21.     QLineEdit *lineEdit;
  22.     QPushButton *button;
  23. };

  24. #endif // DIALOG_H

点击(此处)折叠或打开

  1. //dialog.cpp
  2. #include "dialog.h"
  3. #include "ui_dialog.h"
  4. #include <QtGui>//QtGui模块定义了图形用户界面类

  5. Dialog::Dialog(QWidget *parent) :
  6.     QDialog(parent),
  7.     ui(new Ui::Dialog)
  8. {
  9.     ui->setupUi(this);
  10.     label1 = new QLabel(this);
  11.     label1->setText("Input the radius of a circle");
  12.     label2 = new QLabel(this);
  13.     lineEdit = new QLineEdit(this);
  14.     button = new QPushButton(this);
  15.     button->setText("the area of the circle");
  16.     //QGridLayout是一个网格布局管理器,将所有控件的位置固定
  17.     QGridLayout *mainlayout = new QGridLayout(this);
  18.     mainlayout->addWidget(label1, 0, 0);//将label1放在网格第0行0列的网格中
  19.     mainlayout->addWidget(lineEdit, 0, 1);//将lineEdit放在网格第0行1列的网格中
  20.     mainlayout->addWidget(label2, 1, 0);//将label2放在网格第1行0列的网格中
  21.     mainlayout->addWidget(button, 1, 1);//将button放在网格第1行1列的网格中

  22. // setWindowTitle("Calculate the area of a circle");//对话框标题
  23. // setFixedHeight(sizeHint().height());//设置对话框的理想(合理)高度

  24.     connect(button, SIGNAL(clicked()), this, SLOT(showArea()));
  25. }

  26. Dialog::~Dialog()
  27. {
  28.     delete ui;
  29. }

  30. void Dialog::showArea()
  31. {
  32.     bool ok;
  33.     QString tempStr;
  34.     QString valueStr = lineEdit->text();

  35.     int valueInt = valueStr.toInt(&ok);
  36.     double area = valueInt * valueInt * 3.1416;
  37.     label2->setText(tempStr.setNum(area));
  38. }

点击(此处)折叠或打开

  1. //main.cpp
  2. #include "dialog.h"
  3. #include <QApplication>

  4. int main(int argc, char *argv[])
  5. {
  6.     QApplication a(argc, argv);
  7.     Dialog w;
  8.     w.show();

  9.     return a.exec();
  10. }
对话框大小未处理之前的结果:

对话框结果处理之后(将dialog.cpp中24,25行的注释去掉)的结果:


阅读(2887) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~