2016-09-10 24 views
2

Sirs。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) 

任意の助けが理解されるであろう!

答えて

0

マップを使用して、ボタンのインスタンスを保存できます。 必要に応じてボタンテキストをキーまたはIDとして使用できます。 ボタンテキストをキーとして使用する場合、同じラベルのボタンを2つ使用することはできません。

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] 
+0

ありがとう、サー! –

+0

あなたはようこそ!この回答のおかげであなたの問題に対する解決策が見つかった場合は、それを受け入れることを忘れないでください! –

+0

あなたのアドバイスはとても役に立ちました。それは今働く。再度、感謝します! –

関連する問題