I am Using PyQt5 and Py3.7, I am trying to loop through all my Qlistwidgets and save their string data, but also save all selected items on that widget. I slightly modified the loop from here, but am having some trouble getting the selected items to save and restore using the listwidget array loop. I checked the docs but can't seem to understand how to add additional options into the array (such as save all selected items), from the Qt docs for SetArrayIndex, here.
My listWidgets have selectionMode set to MultiSelection. I am currently saving using this:
def save_list_data(self):
self.settings = QSettings("data.ini", QSettings.IniFormat)
for name, obj in inspect.getmembers(self):
if isinstance(obj, QListWidget):
name = obj.objectName()
self.settings.beginWriteArray(name)
for i in range(obj.count()):
self.settings.setArrayIndex(i)
self.settings.setValue(name, obj.item(i).text())
self.settings.endArray()
And then restoring the listWidget data using:
def open_list_data(self):
self.settings = QSettings("data.ini", QSettings.IniFormat)
for name, obj in inspect.getmembers(self):
if isinstance(obj, QListWidget):
name = obj.objectName()
size = self.settings.beginReadArray(name)
for i in range(size):
self.settings.setArrayIndex(i)
value = self.settings.value(name)
if value != None:
obj.addItem(value)
self.settings.endArray()
This works fine for the data, but how can I get the selectedItems from the ListWidgets to save and restore as well?
For my solution take into account the following:
Using the inspect module may be beneficial for other libraries, but for Qt the widget is not necessarily a member of the class so it is best to use the Qt introspection itself using findChildren.
In the example you use, you are only saving the text but a QListWidgetItem can have more information associated with the roles such as background color, foreground color, etc. So instead I will use the QDataStream operator since this take and save takes the item information.
I will use the "objectname/property" format to save the information since the same widget can have several properties that you want to save.
To save the information of the selected items, it is only necessary to save the row.
Considering the above, the solution is:
Plus: