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

时间:2016-09-10 09:49:34

标签: python pyqt5 qpushbutton

的先生们。

我有非常简单的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())

我有指挥官方法:

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

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

我想要的是什么:

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

或者

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

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

您可以使用地图并保存按钮的实例。 如果需要,可以将按钮文本用作键或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]
相关问题