当前位置: 首页 > 面试题库 >

Python PyQt4函数可用于保存和恢复UI小部件值吗?

松翔
2023-03-14
问题内容

在尝试编写自己的Python PyQt4模块函数之前,我想问一下是否有人可以共享这样的函数。

在我有许多使用PyQt4和qtDesigner构建的GUI的python程序中,我使用QSettings方法在关闭和启动期间保存和恢复UI状态以及所有小部件的值。

本示例说明了如何保存和还原一些lineEdit,checkBox和radioButton字段。

是否有人拥有可以遍历UI并找到所有窗口小部件/控件及其状态并保存它们的功能(例如guisave())以及可以恢复它们的另一个功能(例如guirestore())?

我的closeEvent看起来像这样:

#---------------------------------------------
# close by x OR call to self.close
#---------------------------------------------

def closeEvent(self, event):      # user clicked the x or pressed alt-F4...

    UI_VERSION = 1   # increment this whenever the UI changes significantly

    programname = os.path.basename(__file__)
    programbase, ext = os.path.splitext(programname)  # extract basename and ext from filename
    settings = QtCore.QSettings("company", programbase)    
    settings.setValue("geometry", self.saveGeometry())  # save window geometry
    settings.setValue("state", self.saveState(UI_VERSION))   # save settings (UI_VERSION is a constant you should increment when your UI changes significantly to prevent attempts to restore an invalid state.)

    # save ui values, so they can be restored next time
    settings.setValue("lineEditUser", self.lineEditUser.text());
    settings.setValue("lineEditPass", self.lineEditPass.text());

    settings.setValue("checkBoxReplace", self.checkBoxReplace.checkState());
    settings.setValue("checkBoxFirst", self.checkBoxFirst.checkState());

    settings.setValue("radioButton1", self.radioButton1.isChecked());

    sys.exit()  # prevents second call

我的MainWindow初始化看起来像这样:

def __init__(self, parent = None):
    # initialization of the superclass
    super(QtDesignerMainWindow, self).__init__(parent)
    # setup the GUI --> function generated by pyuic4
    self.setupUi(self)

    #---------------------------------------------
    # restore gui position and restore fields
    #---------------------------------------------

    UI_VERSION = 1

    settings = QtCore.QSettings("company", programbase)    # http://pyqt.sourceforge.net/Docs/PyQt4/pyqt_qsettings.html

    self.restoreGeometry(settings.value("geometry"))
    self.restoreState(settings.value("state"),UI_VERSION)

    self.lineEditUser.setText(str(settings.value("lineEditUser")))  # restore lineEditFile
    self.lineEditPass.setText(str(settings.value("lineEditPass")))  # restore lineEditFile

    if settings.value("checkBoxReplace") != None:
        self.checkBoxReplace.setCheckState(settings.value("checkBoxReplace"))   # restore checkbox
    if settings.value("checkBoxFirst") != None:
        self.checkBoxFirst.setCheckState(settings.value("checkBoxFirst"))   # restore checkbox

    value = settings.value("radioButton1").toBool()
    self.ui.radioButton1.setChecked(value)

问题答案:

好的,我编写了一个具有2个功能的模块来完成我所要求的。一旦我弄清楚了,它并没有那么复杂,但是当您创建新的pyqt
gui程序要在会话之间保存窗口小部件字段值时,确实可以节省很多时间。我目前只有lineEdit,checkBox和combobox字段编码。如果其他任何人想要添加或改进(例如单选按钮等)…我敢肯定,包括我自己在内的其他人也会喜欢它。

#===================================================================
# Module with functions to save & restore qt widget values
# Written by: Alan Lilly 
# Website: http://panofish.net
#===================================================================

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import inspect

#===================================================================
# save "ui" controls and values to registry "setting"
# currently only handles comboboxes editlines & checkboxes
# ui = qmainwindow object
# settings = qsettings object
#===================================================================

def guisave(ui, settings):

    #for child in ui.children():  # works like getmembers, but because it traverses the hierarachy, you would have to call guisave recursively to traverse down the tree

    for name, obj in inspect.getmembers(ui):
        #if type(obj) is QComboBox:  # this works similar to isinstance, but missed some field... not sure why?
        if isinstance(obj, QComboBox):
            name   = obj.objectName()      # get combobox name
            index  = obj.currentIndex()    # get current index from combobox
            text   = obj.itemText(index)   # get the text for current index
            settings.setValue(name, text)   # save combobox selection to registry

        if isinstance(obj, QLineEdit):
            name = obj.objectName()
            value = obj.text()
            settings.setValue(name, value)    # save ui values, so they can be restored next time

        if isinstance(obj, QCheckBox):
            name = obj.objectName()
            state = obj.checkState()
            settings.setValue(name, state)

#===================================================================
# restore "ui" controls with values stored in registry "settings"
# currently only handles comboboxes, editlines &checkboxes
# ui = QMainWindow object
# settings = QSettings object
#===================================================================

def guirestore(ui, settings):

    for name, obj in inspect.getmembers(ui):
        if isinstance(obj, QComboBox):
            index  = obj.currentIndex()    # get current region from combobox
            #text   = obj.itemText(index)   # get the text for new selected index
            name   = obj.objectName()

            value = unicode(settings.value(name))

            if value == "":
                continue

            index = obj.findText(value)   # get the corresponding index for specified string in combobox

            if index == -1:  # add to list if not found
                obj.insertItems(0,[value])
                index = obj.findText(value)
                obj.setCurrentIndex(index)
            else:
                obj.setCurrentIndex(index)   # preselect a combobox value by index

        if isinstance(obj, QLineEdit):
            name = obj.objectName()
            value = unicode(settings.value(name))  # get stored value from registry
            obj.setText(value)  # restore lineEditFile

        if isinstance(obj, QCheckBox):
            name = obj.objectName()
            value = settings.value(name)   # get stored value from registry
            if value != None:
                obj.setCheckState(value)   # restore checkbox

        #if isinstance(obj, QRadioButton):

################################################################

if __name__ == "__main__":

    # execute when run directly, but not when called as a module.
    # therefore this section allows for testing this module!

    #print "running directly, not as a module!"

    sys.exit()


 类似资料:
  • 我制作了一个可以绘制的自定义视图,该视图保存到arraylist中。我想在onSaveInstanceState中保存这些ArrayList,并在onRestoreInstanceState中检索它们。我曾尝试将SharedReferences与Json一起使用,但它不起作用,甚至无法打包。我想保存路径和油漆。 钢笔类: OnsaveInstanceState: onRestoreInstance

  • 我试图理解使用片段保存和恢复状态的过程。我用它创建了滑动导航菜单。 其中一个片段中有以下代码: 例如,我想在用户退出片段之前保存复选框的状态,并在再次创建片段时恢复它。如何实现这一点? 编辑: 根据raxellson的回答,我将片段更改为: 我已被记录,因此未保存savedInstanceState。我做错了什么?

  • 我正在使用可编辑小部件(2amigos/yii2可编辑小部件或kartik-v/yii2可编辑)。它工作得很好,但当我在foreach中尝试它时,它只适用于第一个元素。我想为一个模型使用几个小部件。我怎样才能解决它? 下面是代码:

  • 在绘画的时候,经常会有这种情况,本来正在用绿色笔画,突然需要用红色笔画几笔,但画完了之后又要换成绿色笔。如果是在现实中作画,可以把笔蘸上不同的墨水,画了之后又蘸上之前的墨水,或者准备几只笔,要用哪只就选哪只。 在Canvas中也可以这样,不过Canvas中的画笔永远只有一只。所以,如果要更换画笔的颜色,就需要保存和恢复状态。状态其实就是画布当前属性的一个快照,包括: 图形的属性值,如strokeS

  • 我写了一个Android应用。导出为签名APK发送通过邮件安装到设备。-不在市场。 在运行时,它将用类似的代码将他们的数据保存到内部存储: 据我所知-如果我错了,请纠正我-它将保存到/data/data/com。我的公司。myapp/文件名 因为它是用保存的,所以我不确定市场上或我的其他应用程序是否能看到它保存它。也许如果我创建一个具有相同签名的应用程序? 手机没有根。我已经尝试了很多备份,应用程

  • 状态的保存与恢复 操作流程 为了状态的保存与恢复,我们可以先用栈上的一小段空间来把需要保存的全部通用寄存器和 CSR 寄存器保存在栈上,保存完之后在跳转到 Rust 编写的中断处理函数;而对于恢复,则直接把备份在栈上的内容写回寄存器。由于涉及到了寄存器级别的操作,我们需要用汇编来实现。 而对于如何保存在栈上,我们可以直接令 sp 栈寄存器直接减去相应需要开辟的大小,然后依次放在栈上。需要注意的是,