0

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 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.