I am trying to connect a button with a slot defined in an external class called simu
. The slot is a function called startSimu()
. The object simulation
is instantiated in the same class where I hope to connect the button. Below is the code:
QPushButton *btn1 = new QPushButton("start simulation");
simu simulation;
QObject::connect(btn1, SIGNAL(clicked()), &simulation, SLOT(startSimu()));
The code compiles and runs, but when I click on the button nothing happens. The function startSimu()
is the following:
void simu::startSimu() {
std::cout << "aaaa" << std::endl;
}
The header of the simu
class:
#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
I hope someone has a clue or a hint! Thanks
It looks like your simulation
object destroyed before the slot is called, because you allocated it in the stack:
simu simulation; // Will be destroyed as the execution leave the scope.
QObject::connect(btn1, SIGNAL(clicked()), &simulation, SLOT(startSimu()));
To fix this you will need probably do the following:
simu *simulation = new simu; // Will be destroyed soon
QObject::connect(btn1, SIGNAL(clicked()), simulation, SLOT(startSimu()));
Please do not forget to delete the simulation
object when needed.