Reputation: 7952
I want to update many objects. I have the option to do so with traditional loop like:
void ParentClass::updateItems(const float factor)
{
for (Item *item : items()) {
item->update(factor)
}
}
... or I can do it with signal-slot mechanism like:
class ParentClass : public QObject
{
Q_OBJECT
Q_SIGNALS:
// The signal which will be emitted by parent:
void updateNeeded(const float factor);
private:
void updateItems(const float factor);
}
// Signal is emitted here
void ParentClass::updateItems(const float factor)
{
emit updateNeeded(factor);
}
class Item : public QObject
{
Q_OBJECT
Item(ParentClass *parent) : QObject()
, m_parent(parent)
{
// Connect parent signal to each item slot at each item constructor
QObject::connect(m_parent, &ParentClass::UpdateNeeded,
this, &Item::handleUpdate);
}
public Q_SLOTS:
void handleUpdate(const float factor);
private:
ParentClass *m_parent;
}
// The slot which handles emitted signal:
void Item::handleUpdate(const float factor)
{
this->update(factor);
}
After writing my question, I found this post which is really helpful but I"m not sure if it is directly related to my question.
Upvotes: 4
Views: 205
Reputation: 10972
Use the loop based approach whenever and whereever you can, KISS
signal-slot is a very loose-coupled method of interfacing - while this can be great sometimes (mostly when other options are not possible..) it is much more brittle than regular function calls.
Upvotes: 2