问题是在运行应用程序时,会出现一条关闭应用程序的消息,但没有说明问题的原因。
该应用程序是一个简单的计算器,以便将两个数字相加。
此应用程序包含六个 GUI 对象。
两个QSpinBox
输入数字。
三Qlabel
,二Qlabel
显示+
,,=
一输出二数相加的结果,and this object is the reason of the problem
。
最后,QPushButton
将结果显示在Qlabel
.
现在,是时候显示代码了:
我有三个文件(main.cpp
, calculator.h
, calculator.cpp
)。
-- 主要.cpp --
#include "calculat.h"
int main(int argc, char *argv[]){
QApplication app(argc, argv);
Calculator calc;
calc.show();
return app.exec();
}
-- 计算器.h --
#ifndef CALCULATOR_H
#define CALCULATOR_H
#include <QWidget>
class QSpinBox;
class QLabel;
class Calculator : public QWidget {
Q_OBJECT
public:
Calculator();
private slots:
void on_addNumber_clicked();
public:
QSpinBox *firstValueSpinBox;
QSpinBox *secondValueSpinBox;
QLabel *resultLabel;
};
#endif // CALCULATOR_H
-- 计算器.cpp --
#include "calculator.h"
#include <QPushButton>
#include <QSpinBox>
#include <QLabel>
#include <QHBoxLayout>
Calculator::Calculator(){
QPushButton *addButton = new QPushButton("Add");
firstValueSpinBox = new QSpinBox();
secondValueSpinBox = new QSpinBox();
resultLabel = new QLabel();
QLabel *addLabel = new QLabel("+");
QLabel *equalLabel = new QLabel("=");
connect(addButton, SIGNAL(clicked()), this, SLOT(on_addNumber_clicked()));
QHBoxLayout *layout = new QHBoxLayout(this);
layout->addWidget(firstValueSpinBox);
layout->addWidget(addLabel);
layout->addWidget(secondValueSpinBox);
layout->addWidget(addButton);
layout->addWidget(equalLabel);
layout->addWidget(resultLabel);
}
void Calculator::on_addNumber_clicked(){
int num = this->firstValueSpinBox->value();
int num2 = this->secondValueSpinBox->value();
QString outResult = QString::number(num + num2);
resultLabel->setText(outResult); //<< the problem here
}
我怀疑这一行:
resultLabel->setText(outResult);
删除前一行时,应用程序工作正常。
结论,这个Qlabel
负责显示最终结果的对象中的问题。
QLabel *resultLabel; // declaration in calculator.h
resultLabel->setText(outResult); // in calculator.cpp