【问题标题】:Accessing dynamically created buttons in PyQT5在 PyQT5 中访问动态创建的按钮
【发布时间】:2017-01-18 09:17:00
【问题描述】:

先生们。

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

任何帮助将不胜感激!

【问题讨论】:

    标签: python pyqt5 qpushbutton


    【解决方案1】:

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

    【讨论】:

    • 不客气!如果您通过此答案找到了问题的解决方案,请不要忘记接受它!
    • 您的建议很有帮助。现在可以了。再次感谢!
    猜你喜欢
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 2013-02-08
    相关资源
    最近更新 更多