Pyqt5 遍历 class 个变量并更改 state/set 个值

Pyqt5 loop over class variables and change state/set values

我有一个 class 和一定数量的 class 变量。变量有不同的类型,例如QLineEdit/QCheckbox.....等我如何遍历 class 变量来设置如下变量值:

obj   = FindObj()
value = ['100', 'yes', 'False']
i=0 
for variable in obj:
    if variable.__class__() == 'QLineEdit': # Don't know if it's right
        variable.setText(value[i])
        i=i+1
    elif variable.__class__() == 'QCheckBox':
        variable.setChecked(value[i])
        i=i+1

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon


class FindObj():

    def __init__(self):
        super().__init__()

        self.l1 = QLineEdit()
        self.l2 = QLineEdit()
        self.l3 = QCheckBox()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = FindObj()
    sys.exit(app.exec_())

如果您也将变量放在一个列表中,则可以遍历两个列表:

class FindObj():

    def __init__(self):

        self.l1 = QLineEdit()
        self.l2 = QLineEdit()
        self.l3 = QCheckBox()

        self.variables = [self.l1, self.l2, self.l3]

现在你可以遍历它们了:

obj   = FindObj()
values = ['100', 'yes', 'False']
for variable, value in zip(obj.variables, values):
    if variable.__class__.__name__ == 'QLineEdit': 
        variable.setText(value)
    elif variable.__class__.__name__ == 'QCheckBox':
        variable.setChecked(value)