一个简单的加法计算器,主要还是训练信号与槽的使用
程序代码如下:
//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();
}
程序运行结果图: