문제

I would create a button with 3 choices that changes its text when you make a choice.

This solution works for me:

def swTrigger(self):
    self.setTrigger(self.ui.triggerButton,'Software')
def hwTrigger(self):
    self.setTrigger(self.ui.triggerButton,'Hardware')
def bothTrigger(self):
    self.setTrigger(self.ui.triggerButton,'Both')

def setTrigger(self,pushButton,value):
    pushButton.setText(value)
    #other actions

def uiConfig(self):     
    ##triggerbutton configuration 
    menu = QtGui.QMenu()
    menu.addAction('Software',self.swTrigger)
    menu.addAction('Hardware',self.hwTrigger)        
    menu.addAction('Both', self.bothTrigger)
    self.ui.triggerButton.setText("Software")   
    self.ui.triggerButton.setMenu(menu)

But I should like to avoid making a method for each menu item, because I would like to make dynamic menu entries.

Is there a better way to do this?

도움이 되었습니까?

해결책

You can use either partial or anonymous functions in combination with only one, parametrized, function to accomplish all tasks. Both versions (using partial and lambda) are shown in the example:

from functools import partial

def setTrigger(self, pushButton,value):
    pushButton.setText(value)
    #other actions

def uiConfig(self):     
    ##triggerbutton configuration 
    self.ui.triggerButton.setText("Software")
    self.ui.triggerButton.setMenu(menu)

    menu = QtGui.QMenu()
    menu.addAction('Software', partial(self.setTrigger, self.ui.triggerButton, 'Software'))
    menu.addAction('Hardware', lambda: self.setTrigger(self.ui.triggerButton, 'Hardware'))
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top