Proper way to remove items from a QListWidget[Solved]
-
Hi ,
I am test-populating my ListWidget like this:@
QListWidgetItem * itemno0=new QListWidgetItem(QIcon("D:/QtProjects/modelViewProg/home.png"),"itemno0");
QListWidgetItem * itemno1=new QListWidgetItem(QIcon("D:/QtProjects/modelViewProg/home.png"),"itemno1");
QListWidgetItem * itemno2=new QListWidgetItem(QIcon("D:/QtProjects/modelViewProg/home.png"),"itemno2");
QListWidgetItem * itemno3=new QListWidgetItem(QIcon("D:/QtProjects/modelViewProg/home.png"),"itemno3");
QListWidgetItem * itemno4=new QListWidgetItem(QIcon("D:/QtProjects/modelViewProg/home.png"),"itemno4");
QListWidgetItem * itemno5=new QListWidgetItem(QIcon("D:/QtProjects/modelViewProg/home.png"),"itemno5");mListWidget->addItem(itemno0); mListWidget->addItem(itemno1); mListWidget->addItem(itemno2); mListWidget->addItem(itemno3); mListWidget->addItem(itemno4); mListWidget->addItem(itemno5);
@
and trying to remove some items in a slot like this:
@
for(int i=2;i<mListWidget->count();i++)
mListWidget->takeItem(i);@
but I am puzzled by the fact that I am getting only items 2 and 4 removed and the others stay.I expected only itemno0 and itemno1 to stay.
Does this have something to do with the inner workings of QListWidget or there is something I am getting wrong here.
Any help would be appreciated.Thanks. -
Hi,
mListWidget->count() will not return the same value each time you do an iteration since you are removing items while also counting.
-
No, your usage is still wrong.
You should always remove the second item, until there is no second item any more, which mean you have only one item now!
or you should remove your item from the last to the second item.
-
To add to 1+1=2, your list size still changes, so your counter is going to grow past the size of your list
-
It's explained in the "documentation":http://qt-project.org/doc/qt-4.8/qlistwidget.html#takeItem
-
Rather
@
while (!mListWidget.isEmpty()) {
QListWidgetItem *item ' mListWidget->takeItem();
delete item;
}
@