The problem is when run the application, appears a message to close the application without clarifying the cause of the problem.
the application is a simple calculator in order to addition two numbers.
This application contains six GUI objects.
Two QSpinBox
to input the numbers.
Three Qlabel
, two Qlabel
to display +
, =
,and one other to output the result of addition of two number, and this object is the reason of the problem
.
Finally, one QPushButton
to display the result in a Qlabel
.
Now, It's time to display code:
I have three files(main.cpp
, calculator.h
, calculator.cpp
).
-- Main.cpp --
#include "calculat.h"
int main(int argc, char *argv[]){
QApplication app(argc, argv);
Calculator calc;
calc.show();
return app.exec();
}
-- calculator.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
-- calculator.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
}
I doubt in this line:
resultLabel->setText(outResult);
When remove that previous line, the application work fine.
Conclusion, the problem in this Qlabel
object that responsible for display the final result.
QLabel *resultLabel; // declaration in calculator.h
resultLabel->setText(outResult); // in calculator.cpp