Accessing dynamically created buttons in PyQT5
<p>Sirs.</p>

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

<pre><code>    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())
</code></pre>

<p>And I have the commander method:</p>

<pre><code>   def commander(self):
       print(self.sender().text())
</code></pre>

<p>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?</p>

<p>What I want:</p>

<pre><code>    def commander(self):
        print(self.sender().text())
        pressedbutton = self.findButtonByText("testbutton")
        pressedbutton.setChecked(False)
</code></pre>

<p>Or</p>

<pre><code>        pressedbutton = self.findButtonBySomeKindOfID(3)
        pressedbutton.setChecked(False)
</code></pre>

<p>Any help will be appreciated! </p>

<p>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.</p>

<pre><code>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]
</code></pre>

python pyqt5 qpushbutton