QListWidget: is there a way to clear the list but cache the custom widget on item(Updated)?
-
Hello,
I am reusing a QListWidget to display different content. The content is displayed in a custom widget by putting the custom widget inside the list by QListWidget.setItemWidget(item, widget).I use QtWidgets.QListWidget.takeItem(row) to save the QListWidgetItem, but when I add the item to list again, my custom widget is no where to be found(seems only the item is added and my custom widget on the item is lost).
It seems that my custom widget added by setItemWidget() is destroyed when I takeItem() the corresponding item.
Here is my Code:
import sys from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QListWidget, QListWidgetItem, QVBoxLayout, QLabel class MyList(QWidget): def __init__(self): super().__init__() self.cache = None self.layout = QVBoxLayout(self) self.listWidget = QListWidget() self.clearButton = QPushButton('Cache And Clear', clicked = self.cacheAndClear) self.loadCacheButton = QPushButton('Load Cache', clicked = self.loadCache) self.layout.addWidget(self.listWidget) self.layout.addWidget(self.clearButton) self.layout.addWidget(self.loadCacheButton) self.customWidget = QLabel('Assume this to be my custom widget.') item = QListWidgetItem() self.listWidget.addItem(item) self.listWidget.setItemWidget(item, self.customWidget) def cacheAndClear(self): self.myWidget = self.listWidget.itemWidget(self.listWidget.item(0)) self.cache = self.listWidget.takeItem(0) def loadCache(self): if not self.cache: return newItem = QListWidgetItem() self.listWidget.addItem(newItem) self.listWidget.setItemWidget(newItem, self.myWidget) if __name__ == '__main__': app = QApplication() mylist = MyList() mylist.show() sys.exit(app.exec())And the error log when I click "Load Cache" button:
RuntimeError: Internal C++ object (PySide6.QtWidgets.QLabel) already deleted.So, my question:
Is there a way to cache the custom widget(the widget on the item, not the item itself) after clearing a list?
(I tried clear() the list, takeItem(), and replace my custom widget with other widget before clear(). And my custom widget got destroyed anyway no matter what I do.)Update:
Ok, I find a way around: using multiple QListWidget on a QStackedWidget. So instead of clearing and resuing one list, I just leave my custom widget on the list and switch between multiple lists.
I will leave this unsolved, in case there is actually a way to cache the custom widget. -
No, there is no way to cache the custom widget after clearing a list. Since the custom widget is linked to the QListWidgetItem, once you take that item away, the custom widget is destroyed. If you want to reuse the custom widget, you will have to keep a reference to it and add it back in when you need it.