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);
}
- I have tested the loop approach and it works.
- I'm thinking on signal-slot mechanism, maybe it has some benefits for complex code.
- I wonder which approach is how it should be done or is there a better way?
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.