英文:
Pyqt5 loop over class variables and change state/set values
问题
我有一个带有一定数量的类变量的类。这些变量是不同类型的,例如 QLineEdit/QCheckbox
等等。如何循环遍历类变量以设置变量值如下:
obj = FindObj()
value = ['100', 'yes', 'False']
i=0
for variable in obj:
if variable.__class__() == 'QLineEdit': # 不知道是否正确
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_())
英文:
I have a class with certain number of class variable. Variables are of different types e.g. QLineEdit/QCheckbox
....etc. How can I loop over class variable to set a variable value as below:
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_())
答案1
得分: 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)
英文:
If you put your variables in a list as well, you can loop over both lists:
class FindObj():
def __init__(self):
self.l1 = QLineEdit()
self.l2 = QLineEdit()
self.l3 = QCheckBox()
self.variables = [self.l1, self.l2, self.l3]
Now you can loop over them:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论