would you make your business objects inherit from QObject? pros and cons?
-
Hi,
On my new project I'm hesitating to make my business objects inherit fromQObject
.
In general business objects all derive from a mainBusinessObject
and they only store the data loaded from whatever source. And potentially some methods of computations. So until now, I've never derived those objects fromQObject
.Is it something you have done? you would do?
I'm considering it today to make my life easier on a simple use case: to easily avoid dangling pointers in GUI elements using pointers on some business objects to draw. Especially when those business objects can be updated from an external source or even deleted.
Deriving fromQObject
allows GUI elements to useQPointer
instead of raw pointers and connect theQObject::destroyed
signal to close or invalidate the GUI elements.BusinessObject
could also have anupdated()
signal again connected in the GUI elements to force a redraw.What do you think about this approach?
Instead I could use a
Factory
that would hold a map/hash of all the business objects with all the GUI elements they use and make sure any GUI who needs a handle on a business objects does it through that Factory. In that way GUIs elements could also easily be notified on update or deletion.Which approach would you encourage? for what reasons?
-
It's common to also have 'business objects' derive from QObject. This allows them to be part of the QObject lifetime management, allows them also to use signals/slots, hook into the Qt translation system, be exposed to QML ... So why not?
The disadvantages of Q_OBJECT and friends are that they have some memory overhead, which however only matter if you have hundreds of thousands or millions of them. There's also some compile time overhead due to moc calls, and moc doesn't work too well with multiple inheritance or C++ templates. Finally, QObject derived objects cannot easily be mem-moved or copied. But if these do not apply to you, I would go the easy route and rely on the benefits of QObject also for business objects.
Hope this helps.