1

A little background. I'm writing some code to manage the creation of index entries in LaTeX. A LaTeX index entry can have up to three levels (main heading, sub-heading, sub-sub-heading). The text at each level and the page number for the entry can be either roman, bold, or italic (or both bold and italic). I'm using checkboxes to indicate the font style.

This gives me a total of eight checkboxes I need to track state info for. I would like a generalized method of handling the state change information I need to track.

Example code

in the init function I have

# Flag for if the bold checkbox for the main heading has been checked.
self._mainBold = False

self.mainCkBold.toggled.connect(lambda checked: self.toggle(checked, self._mainBold))


def toggle(self, checked, stateFlag):
    stateFlag = checked

However, the state of self._mainBold is not changed.

Is what I want to do even possible with a lambda function or am I just not doing it correctly? Can anyone recommend an alternative approach? From all the examples I found it appears the parameters you pass in a lambda function remain local.

Don H
  • 11
  • 3

1 Answers1

0

It's possible, and it actually has a name. The function you're looking for is called setattr. The problem is that when you pass self._mainBold as an argument, you're actually passing a copy of that value (at least, a shallow copy). So when you assign to the local variable in toggle, that's assigning to a variable that's about to be thrown away, not the original.

self.mainCkBold.toggled.connect(lambda checked: setattr(self, "_mainBold", checked))

setattr takes an instance and the name of an instance variable and sets it by name.

But, of course, since you know the name in advance, you might as well just assign it directly.

def helper(checked):
    self._mainBold = checked
self.mainCkBold.toggled.connect(helper)

or, on Python 3.8 or newer, using the walrus operator,

self.mainCkBold.toggled.connect(lambda checked: self._mainBold := checked)
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116