Qt C ++自定义插槽不起作用

时间:2014-03-20 14:46:04

标签: qt connect slot

我正在尝试将按钮与名为simu的外部类中定义的插槽连接。插槽是一个名为startSimu()的函数。对象simulation在我希望连接按钮的同一个类中实例化。以下是代码:

QPushButton *btn1 = new QPushButton("start simulation");
simu simulation;
QObject::connect(btn1, SIGNAL(clicked()), &simulation, SLOT(startSimu()));

代码编译并运行,但是当我点击按钮时没有任何反应。函数startSimu()如下:

void simu::startSimu() {
    std::cout << "aaaa" << std::endl;
}

simu类的标题:

#ifndef SIMU_H
#define SIMU_H

#include <QObject>

class simu : public QObject
{
    Q_OBJECT

public:
    simu();
    double timer() {return time;}

public slots:
    void startSimu();


private:
    double time;
};

#endif // SIMU_H

我希望有人有线索或暗示! 感谢

1 个答案:

答案 0 :(得分:3)

在调用插槽之前看起来你的simulation对象被破坏了,因为你在堆栈中分配了它:

simu simulation; // Will be destroyed as the execution leave the scope.
QObject::connect(btn1, SIGNAL(clicked()), &simulation, SLOT(startSimu()));

要解决此问题,您可能需要执行以下操作:

simu *simulation = new simu; // Will be destroyed soon
QObject::connect(btn1, SIGNAL(clicked()), simulation, SLOT(startSimu()));

请不要忘记在需要时删除simulation对象。