문제는 응용 프로그램을 실행할 때 문제의 원인을 명확히하지 않고 응용 프로그램을 닫는 메시지가 나타나는 것입니다.응용 프로그램을 실행할 때 런타임 오류가 발생했으며 그 이유는 Qlable입니다.
응용 프로그램은 두 개의 숫자를 더하기 위해 간단한 계산기입니다.
이 응용 프로그램에는 6 개의 GUI 개체가 포함되어 있습니다.
숫자 2 개를 입력하려면 QSpinBox
.
3 개 Qlabel
, Qlabel
은 +
, =
을 표시하고 다른 하나는 2 개의 숫자를 더한 결과 인 and this object is the reason of the problem
을 출력합니다.
마지막으로 QPushButton
은 결과를 Qlabel
에 표시합니다.
지금, 그것은 코드를 표시하는 시간 :
을 나는 세 개의 파일이 (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
}
이 줄에 의심 스럽습니다.
resultLabel->setText(outResult);
이전 줄을 제거하면 응용 프로그램이 정상적으로 작동합니다.
결론, 최종 결과를 표시하는이 Qlabel
개체의 문제.
QLabel *resultLabel; // declaration in calculator.h
resultLabel->setText(outResult); // in calculator.cpp
합니다. 둘째, 필자가 작성한 프로그램을 실행할 때 어떤 오류도 발생하지 않습니다. 당신이 얻고있는 정확한 오류 메시지는 무엇입니까? –
실제로 컴파일되어 실행되는 코드의 경우 +1입니다. 다음에는 테스트 케이스를 게시 할 때 하나의 파일 ('main.cpp')에 모두 넣고'#include "main.moc"끝에 넣으십시오.이것이 Qt의 "no header"관용구입니다. –
@RA : 코드를 빠르게 작성하기 때문에'(outResult를 따옴표없이) .' 때문에. 그러나이 오류는 오류의 주요 원인이 아닙니다. 둘째로, 런타임 모드에서 코드를 컴파일 할 때 오류가 없습니다 (닫기 창만 표시) –