Michael Thomas
Michael Thomas

Reputation: 503

How to use QList to keep track of instances of child classes

I have two classes, Parent and Child (the latter is derived from the former) , and these are both QObject derived classes. These classes are implemented as nodes on a tree structure, giving each node its specific functionality. Under the Parent class there is a signal that creates a new object of type Child whenever triggered. So after three triggers the tree structure would look like this:

PARENT

---------Child 1

---------Child (1)

---------Child (2)

How would I use QList to keep track of the number of child objects created? I want to append the index number with the name so that Child (1) would look like Child 1, it looks like a copy now.

I have read the QList documentation and I understand how to extract meaningful information once the objects are in a list, but it's this part that I can't find an answer to.

EDIT:

Say I did QList<Child*>ListID, would this just initialise ListID as a pointer to a list of type Parent, or would it also populate that list?

Any suggestions?

PS: I wanted to know this before I started implementation, as I want to know if I am going about it in the wrong way. That is why I have no code to show. I was hoping for more of a casual discussion.

Upvotes: 1

Views: 848

Answers (1)

A bare QObject itself is a tree node. Yes, a QObject is a container of QObjects! So, you need to do nothing special at all, since it keeps a list of all of its direct children, and also provides a way to recursively get all children of a particular type or name.

To access the list of children, use QObject::children(). To get only the children of a specific type, use QObject::findChildren().

In your case, you can invoke auto list = findChildren<Child*>({}, Qt::FindDirectChildrenOnly) to get the list when you need it. If you care not to dynamically allocate any memory, use QObject's internal list directly:

for (auto objChild : std::as_const(children()))
  if (auto child = qobject_cast<Child*>(objChild)) {
    ...
  }

Pre C++-17, use qAsConst instead of std::as_const.

If you're sure that only objects of a particular type are children, you can use a static_cast instead and save a tiny bit of runtime:

for (auto objChild : std::as_const(children())) {
  auto child = static_cast<Child*>(objChild);
  ...
}

Under the Parent class there is a signal that creates a new object of type Child whenever triggered.

Presumably you meant a slot?

Upvotes: 2

Related Questions