Reputation: 19
So, I've written my own class Personages
. It has a function kill()
, that makes Personage to be "dead".
void Personages::kill()
{
this->alive = false;
}
What I want to do is after it has been killed, call a timer to make Personage alive again in 1 second. To call a function like this:
void Personages::reincarnate()
{
this->alive = true;
}
I make this project in Qt and I've tried to use a QTimer, but, as I understood, it can be used only with QObject
(my class isn't QObject
). So my question is how can I achieve this?
void Personages::kill()
{
this->alive = false;
????
}
Okey, I've tried just to make it to be Q_OBJECT
. class Personages is child-class of other class:
class Personages : public Objects
So, in Objects.h
I've done the following:
class Objects: public QObject
{
Q_OBJECT
...
}
Now Personages is Q_OBJECT too, am I right? Personages has these functions (.h):
void kill();
private slots:
void reincarnate();
And here is the code:
void Personages::kill()
{
this->alive = false;
this->timer = new QTimer(this);
connect(this->timer, SIGNAL(timeout()), this, SLOT(reincarnate()));
this->timer->start(1000);
}
void Personages::reincarnate()
{
this->alive = true;
this->timer->stop();
delete this->timer;
}
It compiles but still the dead personage doesn't become alive. What is the problem? I have this error: QObject::connect: No such slot Objects::reincarnate() in ..\AndenturesOfLolo\personages.cpp:1074
Okey, I don't need to do any class to be a Q_OBJECT. Ali's answer worked exactly as I wanted
void Personages::kill()
{
this->alive = false;
QTimer::singleShot(5000, [=]() { reincarnate(); });
}
void Personages::reincarnate()
{
this->alive = true;
}
Upvotes: 0
Views: 1516
Reputation:
Now Personages is Q_OBJECT too, am I right?
No, Personages
does not inherit Q_OBJECT
from Objects
but needs to be Q_OBJECT
as well for the slot reincarnate
to be recognized. Making the super class of Personages
a Q_OBJECT
does not make Personages
a Q_OBJECT
class - if it did then you would never have to declare a QObject
-derived class as Q_OBJECT
, and similarly you would never be able to make a QObject
subclass that wasn't a Q_OBJECT
class.
Try adding the Q_OBJECT
line to your definition for Personages
and see if that works.
Upvotes: 0