【问题标题】:Pyqt5 loop over class variables and change state/set valuesPyqt5 循环遍历类变量并更改状态/设置值
【发布时间】:2020-04-23 10:52:37
【问题描述】:

我有一个具有一定数量的类变量的类。变量有不同的类型,例如QLineEdit/QCheckbox....等等。如何循环类变量以设置变量值,如下所示:

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_())

【问题讨论】:

    标签: python pyqt5 qobject


    【解决方案1】:

    如果你也把你的变量放在一个列表中,你可以遍历这两个列表:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-27
      • 1970-01-01
      • 2015-12-23
      • 2021-11-02
      • 1970-01-01
      相关资源
      最近更新 更多