QObject :: connect()出错。应用程序崩溃。没有构建错误

时间:2015-07-14 08:41:47

标签: c++ qt

我正在尝试制作一个计算器应用程序来进行简单的计算。它不会在Build中显示任何错误但在运行时崩溃 - 该程序意外完成.Desktop_Qt_5_4_2_MinGW_32bit2-Debug \ debug \ calc.exe崩溃

calculator.h

#ifndef CALCULATOR
#define CALCULATOR
#include <QWidget>
class calculator : public QObject
{
    Q_OBJECT

public:
    calculator ( QWidget *parent=0);
    int value=0;

private slots:
    void setValue(int);

};

#endif // CALCULATOR

calculator.cpp

#include <QWidget>
#include <calculator.h>
#include <QPushButton>
#include <QLineEdit>
#include <QGridLayout>

calculator::calculator(QWidget *parent)
{
    QWidget *window = new QWidget;
    QPushButton *add = new QPushButton;
    add->setText("+");
    QPushButton *sub = new QPushButton;
    sub->setText("-");
    QPushButton *mul = new QPushButton;
    mul->setText("*");
    QPushButton *div = new QPushButton;
    div->setText("/");
    QPushButton *enter = new QPushButton;
    enter->setText("enter");
    QLineEdit *disp = new QLineEdit(parent);
    QGridLayout *layout = new QGridLayout;
    layout->addWidget(disp,0,0,0);
    layout->addWidget(add,1,0,0);
    layout->addWidget(sub,1,1,0);
    layout->addWidget(mul,1,2,0);
    layout->addWidget(div,1,3,0);
    layout->addWidget(enter,2,0,0);
    window->setLayout(layout);
    window->show();

    calculator field1, field2, result;
    connect(add,SIGNAL(clicked()),&field1,SLOT((calculator::setValue(disp->text().toInt()))));
    disp->clear();
    connect(enter,SIGNAL(clicked()),&field2,SLOT(calculator::setValue(disp->text().toInt())));
    result.value=field1.value+field2.value;
    disp->setText(QString::number(result.value));

 }

 void calculator::setValue(int val)
 {
    value=val;
 }

的main.cpp

#include <QApplication>
#include <calculator.h>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    calculator cal;

    return app.exec();
}

1 个答案:

答案 0 :(得分:0)

您将信号连接到堆栈中对象的插槽:

calculator field1, field2, result;
connect(add,SIGNAL(clicked()),&field1,SLOT((calculator::setValue(disp->text().toInt()))));

所以当这个槽被称为对象时已经被破坏了。 您应该连接到以下插槽:

,而不是创建新的计算器对象
connect(add,SIGNAL(clicked()),this,SLOT(setValue()));

请注意,对于没有参数的信号,您需要没有参数的插槽。因此,对于您想要处理的每个小部件,如果它们具有不同的行为,则需要创建不同的插槽。

为所有连接修复此问题。