1

i have a lot of checkboxes (like 500) which state i want to save. Their names are like: pr0, pr1, pr2 etc.

What i want to do is:

try:
    if self.ui.pr0.isChecked():
        pr0 = 1
    else:
        pr0 = 0
except:
    pr0 = 0

is there a way to put variable into line number 2?

list = []
for i in range(500):
    try:
        if self.ui.(variable).isChecked():
            pr = 1
        else:
            pr = 0
    except:
        pr = 0
    list.append(pr)

Thanks in advance.

0

2 Answers 2

2

You can use the getattr function from the standard library.

for i in range(500):
  var_name = "pr%i" % i
  var_value = getattr(self.ui, "pr%i" % i).isChecked()
  print "%s has value: %s" % (var_name, var_value)
Sign up to request clarification or add additional context in comments.

Comments

2

A more general way would be to use QObject.findChildren to dynamically get a list of all checkboxes.

checkboxes = self.ui.findChildren(QtGui.QCheckBox, QtCore.QRegExp(r'pr\d+'))
values = {}
for cb in checkboxes:
    values[cb.objectName()] = cb.isChecked()  
    # If you absolutely want to cast to int, though you shouldn't have to.
    # values[cb.objectName()] = int(cb.isChecked())

This will give you a dictionary with Object Name: check value for each checkbox. You can then save the dictionary using json or pickle, and then restore it by iterating through it, using findChildren the same way.

for name, value in values.items():
    try:
        child = self.ui.findChildren(QtGui.QCheckBox, name)[0]
        child.setChecked(value)
    except IndexError:
        pass

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.