Stjepan
Stjepan

Reputation: 111

Python pyqt sender state handling

I have to disable some widgets according to checkbox state. Widgets and checkboxes have similar names: checkP0, minP0, etc. Is there more elegant way to do this than I did? I am pyqt and python beginner. Thanks a lot.

def checkboxes (self, state):

    if state == QtCore.Qt.Checked:
        name = self.sender().objectName()
        mod = "self.mod" + name[-2:] + ".setDisabled(False)"
        min = "self.min" + name[-2:] + ".setDisabled(False)"
        max = "self.max" + name[-2:] + ".setDisabled(False)"
        exec str(mod)
        exec str(min)
        exec str(max)
    else:
        name = self.sender().objectName()
        mod = "self.mod" + name[-2:] + ".setDisabled(True)"
        min = "self.min" + name[-2:] + ".setDisabled(True)"
        max = "self.max" + name[-2:] + ".setDisabled(True)"
        exec str(mod)
        exec str(min)
        exec str(max)

Upvotes: 0

Views: 448

Answers (1)

ekhumoro
ekhumoro

Reputation: 120738

It's very rare that exec or eval are the right tools for the job, so your first instinct should always be to avoid them if at all possible.

In this particular case, you could use getattr and a loop, instead:

def checkboxes (self, state):
    suffix = self.sender().objectName()[-2:]
    enable = state == QtCore.Qt.Checked
    for prefix in 'mod', 'min', 'max':
        getattr(self, prefix + suffix).setEnabled(enable)

Upvotes: 1

Related Questions