1

问题是在运行应用程序时,会出现一条关闭应用程序的消息,但没有说明问题的原因。

该应用程序是一个简单的计算器,以便将两个数字相加。
此应用程序包含六个 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
4

1 回答 1

0

您的代码中没有崩溃错误。它运行得很好。您的问题是与代码不再匹配的陈旧目标文件的一个相当经典的结果。生成的代码moc_calculator.cpp是陈旧的。您是如何构建项目的:手动还是使用 make/qmake?如果您使用 make/qmake 或 make/cmake(例如,来自 Qt Creator),请执行以下操作:

  1. 完全删除构建目录(您会在源代码上方的一个目录中找到它)。

  2. 重建。

有一个功能性错误不会导致崩溃,只是行为不端。也许它甚至是一个错字。而不是resultLabel->setText("outResult");,你想要

resultLabel->setText(outResult); 
于 2013-10-09T03:59:51.373 回答