python-访问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())

我有指挥官方法:

   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)

任何帮助将不胜感激!

解决方法:

您可以使用地图并保存按钮的实例.
您可以根据需要将按钮文本用作键或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]
上一篇:qt-简单的使用 QStyle 类


下一篇:Qt信号与槽简介