在PyQt中,如何将项目和选定的项目保存在组合框中 [英] In PyQt, how can I save the items and selected item in a combobox

查看:130
本文介绍了在PyQt中,如何将项目和选定的项目保存在组合框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我填充了组合框,用户选择了其中一个选项.然后他们关闭所有内容.

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.

我尝试使用泡菜,但显然出现了与Qt相关的错误:

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

我也已经看过'ConfigParser'模块,但是这一切似乎非常令人困惑.因此,在我走错路之前,我只是想知道做这种事情的某种标准方法是-保存填充的元素/选项.

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.

干杯

推荐答案

似乎您要尝试腌制QComboBox实例,因此您遇到的问题实际上与pickle的关系较小还有一个事实,那就是您不能使用它来保存(sip-wrapped)Qt小部件.

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.

请注意,如果组合框中的可选项目集可以在关闭窗口和重新打开窗口之间进行更改,在这种情况下,索引将关闭,否则"selected"字符串可能引用的项目不再是组合框的一部分.

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.

我不确定是否有一个涵盖所有用例的方法",您必须考虑安全性,兼容性(跨Python,Qt和较新版本的应用程序),与其他程序的互操作性以及可能其他因素决定走哪条路.

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.

就我个人而言,我可以使用酸洗(协议0使之在Python版本之间兼容,并且在某种程度上可以被人类读取),或者使用更专业的文件格式以使其可被其他应用程序读取.如果您的应用程序仅适用于Windows,则还可以考虑保存到注册表而不是文件中,请参见此答案例子.

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.

这篇关于在PyQt中,如何将项目和选定的项目保存在组合框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆