sortChildren tree widget
-
I am using the following code:
QTreeWidgetitem* item_ptr = static_cast<QTreeWidgetItem*>(treeWidgetItem);
item_ptr->sortChildren(0, Qt::AscendingOrder);treeWidgetItem is the parent item that needs its children to be sorted. However, the program breaks when it is run. Qt documentation says that "This function does nothing if the item is not associated with a QTreeWidget".
What does that mean, and how do I get them to be "associated" with one another?
-
Comment in doc means that QTreeWidgetItem has to be inserted in QTreeWidget.
As result you first need to insert item in the QTreeWidget and then call sortChildren.Code shown does not show all necessary lines to make reliable guess.
what class is treeWidgetItem for example?
I am asking cause it is not clear why did you need to cast it to QTreeWidgetitem*. -
@alex_malyu treeWidgetItem belongs to a personally defined class within our library. Therefore, casting treeWidgetItem to QTreeWidgetItem was necessary in this case.
QTreeWidgetItem* item_ptr = static_cast<QTreeWidgetItem*>(treeWidgetItem);
if (item_ptr->parent())
{
int index = item_ptr->indexOfChild(static_cast<QTreeWidgetItem*>(treeWidgetItem));
item_ptr->insertChild(index, static_cast<QTreeWidgetItem*>(treeWidgetItem));
}
else
{
QTreeWidget* treeWidget = static_cast<QTreeWidget*>(field->id);
treeWidget->addTopLevelItem(static_cast<QTreeWidgetItem*>(treeWidgetItem));
}
item_ptr->sortChildren(0, Qt::AscendingOrder)This is updated code, where it is first checking if the treeWidgetItem passed into the function has a parent or not. If so, it is inserted into the tree as a child item. If not, it is added as a top level item. Not working though.
-
If treeWidgetItem points to instance of the class derived from QTreeWidgetItem you do not need explicit cast.
If it does not you should not cast cause pointers of such types are unrelated.The only valid reason to use static_cast is when you have pointer to base class, but you need pointer to a child and you can guarantee that pointer points to the instance of child class.
This is not the case above.
This why it seems strange to me and I expect problem there.
As for your code my impression is you freely cast between unrelated pointers.