从字典中恢复复选框状态



首先,我对Python非常陌生-这是我编程的第二个月(只有几周PySide/SQLAlchemy),所以请温柔。

我正在开发一款植物管理应用程序,并有一个表单,其中有一堆复选框,与一年中的几个月有关,种子可以播种,另一堆复选框代表种植区域。我用QTDesigner开发了这个表单。

我正在收集复选框的对象名称和状态,并将它们存储在字典中(使用复选框对象名称作为键,checkstate (true或fals)作为项),然后通过sqlalchemy将其存储在sqlite db中(使用PickleType作为列)。

我想从sqlite数据库中读取一条记录,并将所有复选框恢复到保存时的状态。

我的问题是dict(这是复选框对象名称)中的键是一个字符串。我不知道如何将这个映射到复选框。

例如,dict看起来像这样:

{'zone5bCB': True, 'zone3aCB': False, 'zone7bCB': True, 'zone1CB': True, 'zone3bCB': False, 'zone2bCB': False, 'zone9aCB': False, 'zone4aCB': False, 'zone6aCB': False, 'zone10aCB': False, 'zone6bCB': False, 'zone10bCB': False, 'zone11CB': True, 'zone2aCB': True, 'zone8bCB': False, 'zone8aCB': False, 'zone4bCB': True, 'zone9bCB': True, 'zone7aCB': False, 'zone5aCB': True}

其中键是对象名称。因此,如果我想使用dict中的第一个键:item:

self.zone5bCB.setCheckState(QtCore.Qt.Checked)

我有一种感觉,我必须做一个findchildren(),以某种方式将这些与字典中的对象名称匹配起来。或者也许我去这个错误的方式完全,我应该存储/恢复复选框状态在数据库中的另一种方式??

这里是我刚刚展示的GUI类中相关方法的一个非常精简的版本:

def getCBState(self, wid):
    """ gets the state of all checkboxes on widget wid"""
    returndict = dict()
    CBs = wid.children()
    for box in CBs:
        if(isinstance(box, QtGui.QCheckBox)):
            returndict[box.objectname()] = box.isChecked()
    return returndict
def saveRecord(self):
    """ reads data from all editable widgets and saves to db"""
    # read checkboxes and store in dict's
    zonesdict = self.getCBState(self.layoutWidget2)
    sowseasondict = self.getCBState(self.layoutWidget7)          
    session = Session()
    newplant = PlantInfo(refname=self.refNameEdit.text(), 
                        botname = self.botNameEdit.text(),
                        zones = zonesdict,
                        sowseason = sowseasondict #saving dicts as Blobs
                        #lots more stuff is here but cut for this
                        )
def populateCBs(self, instance): 
    print(instance)
    if instance:
        for key, item in instance.items():
            if item:
                key.setCheckState(QtCore.Qt.Checked) #<-- doesn't work because key is string not a QCheckbox object
def displayDetails(self, current_id=0):
    """ Display records inthe detailed form"""
    session = Session()
    for instance in session.query(PlantInfo).filter(PlantInfo.id == current_id):
        self.clearAll()
        #populate gen info tab
        self.plantIdDisplay.setText(str(instance.id))
        self.plantNameHeader.setText(instance.botname)
        self.refNameEdit.setText(instance.refname)
        self.botNameEdit.setText(instance.botname)
        self.populateCBs(instance.zones)
        self.populateCBs(instance.sowseason)

我不太了解PySide或GUI代码,但我认为我可以看到两种方法可能对您有意义:

首先是创建一个与当前getCBStates方法完全相反的方法:

def setCBState(self, wid, statedict):
    """ sets the state of all checkboxes on widget wid"""
    CBs = wid.children()
    for box in CBs:
        if isinstance(box, QtGui.QCheckBox) and statedict[box.objectname()]:
            box.setCheckState(QtCore.Qt.Checked)

我的另一个想法是基于您当前的populateCBs方法,并且它假设字典中的对象名称对应于当前对象的属性。它使用getattr函数来访问属性:

def populateCBs(self, instance): 
    print(instance)
    if instance:
        for key, item in instance.items():
            if item:
                getattr(self, key).setCheckState(QtCore.Qt.Checked)

我不太了解你的代码,无法判断这些方法中哪一种更适合你,但我希望它们能给你指明正确的方向,找到一些有效的方法。

最新更新