Deleting items from a QListWidget in PyQt4

Posted on March 7th, 2009 by raoul and tagged , , , , , .

This morning I was working on my open source lyrics projection program, openlp.org, and I was struggling to work out how to remove an item from a QListWidget in PyQt4.

It's fairly simple in Qt4 and C++, you simply fetch the item, and then delete it using the C++ delete keyword:

QListWidgetItem item = ui->listWidget->currentItem();
delete item;

However, I couldn't figure out how to do it in Python. Initially I tried the del keyword, but that didn't work.

item = self.listWidget.currentItem()
del item

Then, after seeing this post, I tried assigning it to None. That didn't work either.

item = self.listWidget.currentItem()
item = None

Finally after reading the above post for the second time, I realised that I need to remove the item from the list, I couldn't just assign it to None where it is in the list. So I came up with this:

item = self.listWidget.takeItem(self.listWidget.currentRow())
item = None

And behold, it works!