计算器界面设计与实现
一. 计算器界面设计
- 设计
二. 注意事项
- 计算器界面没有最大化、最小化按钮和帮助按钮,只有关闭按钮
- 界面大小不能改变,是固定的
- 功能性组件比较多,如果构造功能性组件的过程中构造失败,需要释放掉之前构造工作的组件,解决方法采用二次构造
三. 实现
-
代码如下
#ifndef CALCULATORUI_H #define CALCULATORUI_H #include <QWidget> #include <QLineEdit> #include <QPushButton> class QCalculatorUI : public QWidget { private: QLineEdit* m_edit; QPushButton* m_buttons[20]; QCalculatorUI(); bool construct(); public: static QCalculatorUI* NewInstance(); void show(); ~QCalculatorUI(); }; #endif // CALCULATORUI_H
#include "CalculatorUI.h" #include "ui_CalculatorUI.h" QCalculatorUI::QCalculatorUI() : QWidget(NULL, Qt::WindowCloseButtonHint) { } bool QCalculatorUI::construct() { bool ret = true; const char* btnText[20] = { "7", "8", "9", "+", "(", "4", "5", "6", "-", ")", "1", "2", "3", "*", "<-", "0", ".", "=", "/", "C", }; m_edit = new QLineEdit(this); if( m_edit != NULL ) { m_edit->move(10, 10); m_edit->resize(240, 30); m_edit->setReadOnly(true); } else { ret = false; } for(int i=0; (i<4) && ret; i++) { for(int j=0; (j<5) && ret; j++) { m_buttons[i*5 + j] = new QPushButton(this); if( m_buttons[i*5 + j] != NULL ) { m_buttons[i*5 + j]->resize(40, 40); m_buttons[i*5 + j]->move(10 + (10 + 40)*j, 50 + (10 + 40)*i); m_buttons[i*5 + j]->setText(btnText[i*5 + j]); } else { ret = false; } } } return ret; } QCalculatorUI* QCalculatorUI::NewInstance() { QCalculatorUI* ret = new QCalculatorUI(); if( (ret == NULL) || !ret->construct() ) { delete ret; ret = NULL; } return ret; } void QCalculatorUI::show() { QWidget::show(); setFixedSize(width(), height()); } QCalculatorUI::~QCalculatorUI() { }
#include "CalculatorUI.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); QCalculatorUI* cal = QCalculatorUI::NewInstance(); int ret = -1; if( cal != NULL ) { cal->show(); ret = a.exec(); delete cal; } return a.exec(); }