Skip to content Skip to sidebar Skip to footer

In Pyqt, How Can I Save The Items And Selected Item In A Combobox

I populate my combo box and the user selects one of the options. Then they close everything. At a later date the user may open the window again and it would be tedious to ask them

Solution 1:

It seems what you're trying to do is to pickle the QComboBox instance, so the problem you've encountered is actually less related to pickle and more to the fact that you can't use it to save (sip-wrapped) Qt widgets.

Depending on how your combo box is populated, it might be better to save the index of the selected item or the selected string and re-select this item when the window is (re-) opened.

Be careful though if the set of selectable items in the combo box can change in-between closing and re-opening of the window, in which case the index will be off or the "selected" string might refer to an item which is not part of the combo box any more.

EDIT:

I am not sure if there is a single "way to do it" that covers all use cases, you have to consider security, compatibility (across Python, Qt and newer versions of your app), interoperability with other programs and probably other factors to decide which way to go.

Personally, I either use pickling (protocol 0 makes it compatible across Python versions and somewhat human-readable) or a more specialised file format to make it readable by other applications. If your application is Windows-only, you might also consider saving to the Registry instead of a file, see this answer for an example.

Solution 2:

You can simply dump the selected index of combobox and then load it when reload/relaunch the application. The syntax may be like this

pickle.dump(str(self.WordCardsFieldSelector.currentIndex()), open( "save.p", "wb" ) )

Post a Comment for "In Pyqt, How Can I Save The Items And Selected Item In A Combobox"