Maciek
Maciek

Reputation: 183

From string to pyqt object as variable

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.

Upvotes: 1

Views: 1566

Answers (2)

Brendan Abel
Brendan Abel

Reputation: 37539

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

Upvotes: 2

salomonderossi
salomonderossi

Reputation: 2188

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)

Upvotes: 2

Related Questions