3

我会创建一个带有 3 个选项的按钮,当您做出选择时会更改其文本。

这个解决方案对我有用:

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)

但我想避免为每个菜单项创建一个方法,因为我想创建动态菜单项。

有一个更好的方法吗?

4

1 回答 1

6

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'))
于 2013-08-25T11:30:31.520 回答