标签:
界面中通过三个 QLineEdit控件,一个QPushButton实现+ - * /四则运算,点击pushbutton后将运算结果显示在QLabel控件上。
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QLineEdit> #include <QPushButton> #include <QLabel> class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); private: QLineEdit * edit1; QLineEdit * edit2; QLineEdit * edit3; QPushButton * btn1; QLabel *label1; double GetRes(int num1,char ch,int num2); private slots: void add(); }; #endif // WIDGET_H
#include "widget.h" #include <QGridLayout> Widget::Widget(QWidget *parent) : QWidget(parent) { edit1=new QLineEdit(this); edit2=new QLineEdit(this); edit3=new QLineEdit(this); btn1=new QPushButton(this); btn1->setText("计算"); label1=new QLabel(this); label1->setText("result"); QGridLayout * layout1=new QGridLayout(this); layout1->addWidget(edit1,0,0); layout1->addWidget(edit2,0,1); layout1->addWidget(edit3,0,2); layout1->addWidget(btn1,1,0); layout1->addWidget(label1,1,1); //注册按钮点击事件 connect(btn1,SIGNAL(clicked()),this,SLOT(add())); } //按钮点击事件 void Widget::add() { //获取第一个数 QString s1=edit1->text(); //获取操作符 QString s2=edit2->text(); //获取第三个数 QString s3=edit3->text(); //显示结果 label1->setText(QString::number(GetRes(s1.toInt(),*(s2.toStdString().data()),s3.toInt()))); } //计算结果 double Widget::GetRes(int num1,char ch,int num2) { double res=0; switch(ch) { case ‘+‘: res=num1+num2; break; case ‘-‘: res=num1-num2; break; case ‘*‘: res=num1*num2; break; case ‘/‘: res=num1/num2; break; default: break; } return res; } Widget::~Widget() { }
标签:
原文地址:http://www.cnblogs.com/zhanggaofeng/p/5967721.html