Qt学习例子5——calculatorwidget

一个简单的加法计算器,主要还是训练信号与槽的使用

 

程序代码如下:

 

//calculator.h

 

#ifndef CALCULATORWIDGET_H
#define CALCULATORWIDGET_H
#include <QWidget>
#include <QDialog>
#include <QLineEdit>
#include <QLabel>
class CalculatorWidget : public QDialog
{
    Q_OBJECT
public:
    explicit CalculatorWidget(QWidget *parent = 0);
    virtual ~CalculatorWidget();
private:
    QLineEdit *m_firstValue;
    QLineEdit *m_secondValue;
    QLabel *m_result;
signals:
public slots:
    void showMessage();
};
#endif // CALCULATORWIDGET_H

 

//calculator.cpp

 

#include "calculatorwidget.h"
#include <QtGui>
#include <QtDebug>
CalculatorWidget::CalculatorWidget(QWidget *parent) :
    QDialog(parent)
  ,m_firstValue(new QLineEdit())
  ,m_secondValue(new QLineEdit())
  ,m_result(new QLabel(""))
{
   QHBoxLayout *topLayout = new QHBoxLayout();
   topLayout->addWidget(m_firstValue);
   topLayout->addWidget(new QLabel("+"));
   topLayout->addWidget(m_secondValue);
   topLayout->addWidget(new QLabel("="));
   topLayout->addWidget(m_result);
   setLayout(topLayout);
   connect(m_secondValue,SIGNAL(returnPressed()),this,SLOT(showMessage()));
}
void CalculatorWidget::showMessage()
{
    QString firstValueText,secondValueText;
    int firstValue,secondValue,total;
    bool a,b;
    firstValueText=m_firstValue->text();
   secondValueText=m_secondValue->text();
    firstValue=firstValueText.toInt(&a);
    secondValue=secondValueText.toInt(&b);
    if(a && b)
    {
        total=firstValue+secondValue;
        qDebug("%d",total);
        m_result->setText(QString::number(total));
        qDebug("%s",qPrintable(m_result->text()));
    }
    else
    {
        m_result->setText("no result!");
    }
}
CalculatorWidget::~CalculatorWidget()
{
    delete m_firstValue;
    delete m_secondValue;
    delete m_result;
}

 

//main.cpp

 

#include <QApplication>
#include "calculatorwidget.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
CalculatorWidget *cal=new CalculatorWidget;
cal->show();
return a.exec();
}

 

 

程序运行结果图:

Qt学习例子5鈥斺攃alculatorwidget

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值