0

I'm trying to connect a button click in PyQt5 with a page switch in stackedWidget using a loop.

# Creating a list of buttons so I can walk through them using a loop
self.pageButtons = [self.page0Button, self.page1Button, self.page2Button, self.page3Button,
                    self.page4Button, self.page5Button, self.page6Button, self.page7Button,
                    self.page8Button, self.page9Button, self.page10Button, self.page11Button,
                    self.page12Button, self.page13Button, self.page14Button, self.page15Button,
                    self.page16Button, self.page17Button, self.page18Button]

for i, btn in enumerate(self.pageButtons):                
    btn.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(i))

But this cycle doesn't work correctly.

For some reason, the buttons connect only to the last function in this cycle. In this case, all the buttons from the self.pageButtons list connect with the function self.stackedWidget.setCurrentIndex(18) because it's the last in the list.

I noticed this problem in PyQt5 a long time ago, but I usually fixed it by connecting each button individually without a loop:

    self.page0Button.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(0))
    self.page1Button.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(1))
    ...
    ...
    ...
    self.page18Button.clicked.connect(lambda: self.stackedWidget.setCurrentIndex(18))

How can I fix that?

  • 3
    Does this answer your question? [Connecting slots and signals in PyQt4 in a loop](https://stackoverflow.com/questions/4578861/connecting-slots-and-signals-in-pyqt4-in-a-loop) – Christian Karcher Nov 03 '21 at 11:34

0 Answers0