For one of my projects I have a tree of QObject derived objects, which utilize QObject's parent/child functionality to build the tree.
This is very useful, since I make use of signals and slots, use Qt's guarded pointers and expect parent objects to delete children when they are deleted.
So far so good. Unfortunately now my project requires me to manage/change the order of children. QObject does not provide any means of changing the order of its children (exception: QWidget's raise() function - but that's useless in this case). So now I'm looking for a strategy of controlling the order of children. I had a few ideas, but I'm not sure about their pros & cons:
Use a int m_orderIndex
member variable as a sort key and provide a sortedChildren()
method which returns a list of QObjects sorted by this key.
QObject::children()
method is overriden - will lead to problems during loops when items' order is changed, also is more expensive than default implementation.Maintain a redundant list of children in a QList
, and add children to it when they are created and destroyed.
Any ideas or feedback, especially from people who already solved this in their own projects, is highly appreciated. Happy new year!
I spent a lot of time going through all these options in the past days and discussed them carefully with some other programmers. We decided to go for Option A.
Each of the objects we are managing is a child of a parent object. Since Qt does not provide any means of re-ordering these objects, we decided to add a int m_orderIndex
property to each object, which defaults to 0.
Each object has an accessor function sortedChildren()
which returns a QObjectList
of the children. What we do in that function is:
QObject::chilren()
function to get a list of all available child objects.dynamic_cast
all objects to our "base class", which provides the m_orderIndex
property.qSort
with a custom LessThan
function to find out if qSort needs to change the order of two objects.We did this for the following reasons:
children()
without having to worry about side effects.children()
function in places where the order does not matter, without having any performance loss.children()
by sortedChildren()
and get the desired effect.One of the good things about this approach is, that the order of children does not change if all sort indices are set to zero.
Sorry for answering my own question, hope that enlightens people with the same problem. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With