In PyQt, how can I save the items and selected item in a combobox

五迷三道 提交于 2019-12-24 02:16:56

问题


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 to retype and reselect the options again so I would like to 'load' them.

I've tried to use pickle, but I get an error related to Qt apparently:

self.WordCardsFieldSelector = QtGui.QComboBox()

#Fails when trying to do this dump
pickle.dump( self.WordCardsFieldSelector, open( "save.p", "wb" ) )


TypeError: the sip.wrapper type cannot be instantiated or sub-classed

I've looked at the 'ConfigParser' module too but it all seems very confusing. So before I go down the wrong path, I'm just wondering what is the somewhat standard way to do things like this - saving populated elements/options.

Cheers,


回答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.




回答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" ) )


来源:https://stackoverflow.com/questions/17666756/in-pyqt-how-can-i-save-the-items-and-selected-item-in-a-combobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!