Using QObject instead of container

After reading an interesting parent-child system, QObjectI wonder how often Qt developers use this instead of the more traditional container. Assuming memory bias is not a requirement, this seems to offer some interesting features.

For example, you may have to QObjectprovide it with children of different types, and then it is easy to find all the children based on their types, providing QObject a dynamic heterogeneous container function, in contrast to the required homogeneous collection, a traditional container.

And QObjectnaturally manages the memory of their children, which is also convenient.

Is this the usual use of this feature?

+4
source share
2 answers

QObject::findChildren can be much slower than storing your objects in a regular container such as a QList, because:

  • Every time he goes through all the children. It even searches recursively (but it can be disabled).
  • Performs a runtime type check.
  • Each time he creates a new QList. It can be slow and expensive, as a result there are many objects.

All of the above is not necessary if you just use QList<Type*> my_objects. Also in this case:

  • You can name your collection. QList<QPushButton*> panic_buttonsmore understandable than findChildren<QPushButton*>().
  • You can have multiple collections of objects of the same type.

If you want to create a heterogeneous container, you can use QHash<any_type_identifier, QObject*>. It will be faster.

, findChildren . , . QObject.

+5

@PavelStrakhov, QObject:: findChildren . , , QList, QObject. : -

class BaseObject : public QObject
{
    Q_OBJECT

    public:

        static BaseObject* FindObject(unsigned int id); // find object by id

    private:
        unsigned int m_id;

        static unsigned int s_nextId; // next id for a new BaseObject
        static QList<QBaseObject*> s_objectsList; // list of all BaseObject-type instances
};

BaseObject QObject. , BaseObject , s_nextId , , s_objectsList. .

, , , , , QGraphicsView/QGraphicsScene. BaseObject QGraphicsObject.

, , , , .

+1

All Articles