简体   繁体   中英

Qt4, QMenu addAction, connect function with arguments

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM