This question already has an answer here:
- C++ Qt signal and slot not firing 3 answers
I have been working on learning C++ and Qt4 recently, but I have hit a stumbling block.
I have the following class and implementation:
class Window : public QWidget
{
public:
Window();
public slots:
void run();
private:
//...
};
and
Window::Window()
{
//...
connect(runBtn,SIGNAL(clicked()),this,SLOT(run()));
//...
}
Window::run()
{
//...
}
However, when I attempt to build and run it, although it builds just fine, it immediately exits out with the message
Object::connect: No such slot QWidget::run()
Unless I did something wrong, Qt does not seem to be recognizing the slot run()
Could anyone please help?
Update:
The code is now:
class Window : public QWidget
{
Q_OBJECT
public:
Window(QWidget *parent = 0);
public slots:
void run();
private:
//...
};
and
Window::Window(QWidget *parent) : QWidget(parent)
{
//...
connect(runBtn,SIGNAL(clicked()),this,SLOT(run()));
//...
}
Window::run()
{
//...
}
The program still "unexpectedly finished", but no longer tell me that there is no such thing as QWidget::run()
Looks like runBtn is not instantiated at the time connect is called -- as implied by one of the other answers.
Use breakpoints to check where the crash is happening.
Possibly you have forgotten a Q_OBJECT macro in your Window class?
Well I was having this problem too and could find no help on-line. I found out that I was forgetting to delete the moc_* files before recompiling and it was using the old moc files to create the executable file. This caused it to not know about any new slots I had coded. I would check that if all the rest of these suggestions failed.
Sometimes the simplest solution is the best solution...
What is
runBtn
, and how is it created? If it's created as part of a ui file, are you callingsetupUi()
? How is your window class being created? You seem to have omitted some code (// ...
) which may be where the error is.The best advice I can give to to try and reduce your problem to a very small compilable example. This helps for two reasons:
Hope this helps.