在 PyQT5 中访问动态创建的按钮

Dmi*_*vus 3 python qpushbutton pyqt5

先生们。

我有非常简单的 PyQT5 应用程序。我动态创建了按钮并连接到某些功能。

    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())
Run Code Online (Sandbox Code Playgroud)

我有指挥官方法:

   def commander(self):
       print(self.sender().text())
Run Code Online (Sandbox Code Playgroud)

所以我可以访问单击的按钮。但是如果我想访问以前点击过的按钮怎么办?还是主窗口中的另一个元素?怎么做?

我想要的是:

    def commander(self):
        print(self.sender().text())
        pressedbutton = self.findButtonByText("testbutton")
        pressedbutton.setChecked(False)
Run Code Online (Sandbox Code Playgroud)

或者

        pressedbutton = self.findButtonBySomeKindOfID(3)
        pressedbutton.setChecked(False)
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激!

mel*_*lix 5

您可以使用地图并保存按钮的实例。如果需要,您可以使用按钮文本作为键或 id。如果您使用按钮文本作为键,则不能有两个具有相同标签的按钮。

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]
Run Code Online (Sandbox Code Playgroud)