0

I have used gui designer in PyQt to draw out several analogous groups of pushbuttons. Across these groups, the pushButton.connect call will be similar/honor a semi-repeatable pattern. The difference will be that each group of buttons will refer to a distinct model (also in the gui, listviews) to pass along data that connect's target will use.

This is my attempt at coding this. It appears to work right now but i am concerned that I am not following best practices.


def do_business_logic(data, truth, size):
   if truth:
       print (data, size)

def configure(groups)
    for view, buttongroup in groups:
            for b in buttongroup:
                button = b[0]
                truth = b[1]
                size = b[2]
                button.clicked.connect(
            lambda checked truth = truth , size = size: do_business_logic(
            model_data = view.currentIndex().data(),
            truth = truth,
            size = size
            )
        )
    

buttongroups = [
(self.listView, 
[
(self.pushButton_BAA, True, 100),
(self.pushButton_BAB, True, 1000),
(self.pushButton_BAC, True, 10000),
(self.pushButton_SAA, False, 100),
(self.pushButton_SAB, False, 1000),
(self.pushButton_SAC, False, 10000)
]
),
(self.listView_2,
[
(self.pushButton_BBA, True, 100),
(self.pushButton_BBB, True, 1000),
(self.pushButton_BBC, True, 10000),
(self.pushButton_SBA, False, 100),
(self.pushButton_SBB, False, 1000),
(self.pushButton_SBC, False, 10000)
]
)
]

for buttongroup in buttongroups:
    configure(buttongroup)

My research yielded that there are potential issues with respect to:

  • scoping/closure and lambda (i think the 'truth = truth , size = size' binding fixed that)
  • i needed to add 'clicked' after lambda per: "the clicked signal takes as a parametehttps://stackoverflow.com/questions/49184163/creating-pyqt5-buttons-in-a-loop-all-buttons-trigger-the-same-callbackr a Boolean value that indicates that if the button is checked or not" ( @eyllanesc 's insight from: Creating PyQt5 buttons in a loop: all buttons trigger the same callback )

Finally, I am aware of lambda / 'reference to self' trouble such as here: Using lambda expression to connect slots in pyqt

Since the lambda function needs to know the model data value , am I currently committing this error? Is there a better way?

10mjg
  • 549
  • 5
  • 15
  • TYPO: change `lambda checked truth = truth , size = size:` to `lambda checked, truth = truth , size = size:`. add comma after `checked` – eyllanesc Jun 07 '21 at 17:15

0 Answers0