界面中通过三个 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()
{
}
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPushButton>
#include <QLabel>
#include <QTimer>
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
private:
QPushButton * btn1;
QLabel * label1;
QTimer * time1;
char ** arr;
private slots:
void choicename();
void on_time();
};
#endif // WIDGET_H
#include "widget.h"
#include <QGridLayout>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
arr=new char *[10];
arr[0]="小米0";
arr[1]="小红1";
arr[2]="流云2";
arr[3]="天哥3";
arr[4]="小叶4";
arr[5]="红玉5";
arr[6]="南天6";
arr[7]="晓峰7";
arr[8]="字有8";
arr[9]="小刚9";
time1=new QTimer(this);
btn1=new QPushButton(tr("抽奖"),this);
label1=new QLabel(this);
label1->setText("Name");
QGridLayout *layout1=new QGridLayout(this);
layout1->addWidget(btn1,0,0);
layout1->addWidget(label1,1,1);
//注册按钮点击事件
connect(btn1,SIGNAL(clicked()),this,SLOT(choicename()));
//注册定时器事件
connect(time1,SIGNAL(timeout()),this,SLOT(on_time()));
}
void Widget::choicename()
{
if(time1->isActive())
{
time1->stop();
}
else
{
time1->start(300);
}
}
void Widget::on_time()
{
static int i=0;
if(i>=10)
{
i=0;
}
label1->setText(arr[i]);
i++;
}
Widget::~Widget()
{
}