I have some trouble updating a QListWidget
after deleting an item of it.
This is part of the code:
class Window(QMainWindow):
list_1 = [] #The items are strings
list_2 = [] #The items are strings
def __init__(self):
#A lot of stuff in here
def fillLists(self):
#I fill the lists list_1 and list_2 with this method
def callAnotherClass(self):
self.AnotherClass().exec_() #I do this to open a QDialog in a new window
class AnotherClass(QDialog):
def __init__(self):
QDialog.__init__(self)
self.listWidget = QListWidget()
def fillListWidget(self):
#I fill self.listWidget in here
def deleteItems(self):
item_index = self.listWidget.currentRow()
item_selected = self.listWidget.currentItem().text()
for index, content in enumerate(Window.list_2):
if content == item_selected:
del Window.list_2[index]
break
After deleting the item with the deleteItems
method, i want to see the remaining items of the list inmediately in the QListWidget
. In other words, i need to delete the item from the list as soon as i press the button "Delete".
I have tried with update()
and repaint()
after the break call, but it does not work.
How can i do this? Hope you can help me.
------------Edit---------------
The QListWidget
is updated if i close the QDialog
. When i open it again, i do not see the item that i deleted. So, the list is updating, but not while the QDialog
is still open.
The problem is that you are removing the item from the list that you used to populate the QListWidget
. When you first create the QListWidget
, a copy of the data is stored internally by Qt. Updating the original source will not delete the item from the QListWidget
. However when you close and reopen the dialog, the QListWidget
is recreated, so you see the correct data (since it is effectively reloaded from the source).
You should use QListWIdget.takeItem()
to remove the rows you want. In your case, this is:
item_index = self.listWidget.currentRow()
self.listWidget.takeItem(item_index)
You should still remove the item from your source list (Window.list_2
) as well as per your current code.