Dmitry Korvus
Dmitry Korvus

Reputation: 31

Accessing dynamically created buttons in PyQT5

Sirs.

I have pretty much simple PyQT5 app. I have dynamically created buttons and connected to some function.

    class App(QWidget):
        ...
        def createButtons(self):
            ...
            for param in params:
                print("placing button "+param)
                button = QPushButton(param, checkable=True)
                button.clicked.connect(lambda: self.commander())

And I have the commander method:

   def commander(self):
       print(self.sender().text())

So I have access to clicked button. But what if I want to access previously clicked button? Or another element in main window? How to do it?

What I want:

    def commander(self):
        print(self.sender().text())
        pressedbutton = self.findButtonByText("testbutton")
        pressedbutton.setChecked(False)

Or

        pressedbutton = self.findButtonBySomeKindOfID(3)
        pressedbutton.setChecked(False)

Any help will be appreciated!

Upvotes: 3

Views: 1994

Answers (1)

melix
melix

Reputation: 468

You can use a map and save the instances of your buttons. You can use the button text as key or the id if you want. If you use the button text as key you cannot have two buttons with the same label.

class App(QWidget):

    def __init__(self):
         super(App,self).__init__()
         button_map = {}
         self.createButtons()

    def createButtons(self):
        ...
        for param in params:
            print("placing button "+param)
            button = QPushButton(param, checkable=True)
            button.clicked.connect(lambda: self.commander())
            # Save each button in the map after the setting of the button text property
            self.saveButton(button)

    def saveButton(self,obj):
         """
         Saves the button in the map
         :param  obj: the QPushButton object
         """
         button_map[obj.text()] = obj

    def findButtonByText(self,text)
         """
         Returns the QPushButton instance
         :param text: the button text
         :return the QPushButton object 
         """
         return button_map[text]

Upvotes: 6

Related Questions