Reputation: 11
i try to build a realtime search for a QTreeWidget, that means that i have a QLineEdit and when im typing, i will filter the shown results in the QTreeWidget.
At the moment i get the "still shown itmes" with QTreeWidget.findItems()
foundItems = mainForm.ui.treeShips.findItems(text,QtCore.Qt.MatchContains)
later i clear the QTreeWidget ( mainForm.ui.treeShips) with
mainForm.ui.treeShips.clear()
then i want to add the "still shown items" with
mainForm.ui.treeShips.addTopLevelItems(foundItems)
but then the programm crashes with the "underlying C/C++ object has been deleted" error
My first idea is, that with clearing the treeShips, the content of foundItems got cleared too cause the objects of foundItems ( print(foundItems) ) and the objects of treeShips have the same adresses and when the programm want to work with this list, it crash.
Does someone know how to fix it, or have a better idea to apply such a "search filter" ?
( i hope i could describe my problem correctly :) )
thanks and best regards
Upvotes: 0
Views: 973
Reputation: 11
i found a workaround based on the 2nd idea from Neox.
I iterate all items in the tree and set the hidden flag on true ( setHidden(True) ) and then i iterate the foundItems and set the hidden flag on false ( i think that works, cause both lists have the same adresses )
for item in mainForm.ui.treeShips.findItems("",QtCore.Qt.MatchContains):
item.setHidden(True)
for item in foundItems:
item.setHidden(False)
But i dont know if that isnt a dirty way, but it works :)
I hope that this will help other ppl who have the same problem.
Upvotes: 1
Reputation: 2004
Whenever you call clear
function on a QTreeWidgetItem
the items are deleted so the error you get is no surprise. You can see it in the following excerpt of the QTreeWidget
implementation:
void QTreeWidget::clear()
{
Q_D(QTreeWidget);
selectionModel()->clear();
//the treeModel here is QTreeModel, refer to snippet below
d->treeModel()->clear();
}
void QTreeModel::clear()
{
SkipSorting skipSorting(this);
for (int i = 0; i < rootItem->childCount(); ++i) {
QTreeWidgetItem *item = rootItem->children.at(i);
item->par = 0;
item->view = 0;
delete item;
}
....
}
To you actual question about search implementation. First here is a nice snippet for implementation of the actual search functionality (not real-time). (sorry its c++ but i hope its fine).
To perform a real time search you have to connect a void textChanged(const QString & text)
signal from QLineEdit
to a slot where the search is performed.
I hope that answers your question
Upvotes: 0