PyQt:获取菜单按钮对象名称而不是菜单项

时间:2018-04-20 04:33:06

标签: python menu pyqt pyqt5 qpushbutton

我有几个带有菜单的qpushbuttons,我正在尝试获取已选择菜单项的特定按钮。现在使用发送器功能我可以选择菜单项,但我需要保存菜单的实际按钮(在这种情况下为按钮1)。

enter image description here

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setMinimumSize(QSize(400, 400))    
        buttons= ['button1','button2','button3']
        pybutton = {}
        x=0
        t = 0
        for i in buttons:
            t = t + 100
            x+=1
            pybutton[str(x)] = QPushButton(i, self) 
            pybutton[str(x)].setObjectName('btn' + str(x))
            menu = QMenu()
            menu.addAction('item1',self.status)
            menu.addAction('item2',self.status)
            menu.addAction('item3',self.status)
            menu2 = menu.addMenu('menu2')
            menu2.addAction('item4')
            pybutton[str(x)].setMenu(menu)
            pybutton[str(x)].resize(100,100)
            pybutton[str(x)].move(400-int(t),100)
            pybutton[str(x)].setStyleSheet('QPushButton::menu-indicator { image: none; }')
        self.statusBar()
    def status(self):
        sender = self.sender()
        print('PyQt5 button click')
        self.statusBar().showMessage(sender.text() + ' was pressed')

1 个答案:

答案 0 :(得分:2)

一种可能的解决方案是使用setProperty()方法将按钮作为属性传递给每个QAction,并使用property()

在插槽中获取它
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setMinimumSize(QSize(400, 400))    
        texts= ['button1','button2','button3']
        pybutton = {}
        for x, (text, t) in enumerate(zip(texts, range(300,0,-100))):
            btn = QPushButton(text, self) 
            btn.setObjectName('btn{}'.format(x+1))
            btn.resize(100,100)
            btn.move(t,100)
            btn.setStyleSheet('QPushButton::menu-indicator { image: none; }')

            menu = QMenu()
            btn.setMenu(menu)
            args = ("button", btn)
            menu.setProperty(*args)
            for act in ("item1", "item2", "item3"):
                action = menu.addAction('item1',self.status)
                action.setProperty(*args)
            menu2 = menu.addMenu('menu2')
            action = menu2.addAction('item4', self.status)
            action.setProperty(*args)
            pybutton[str(x+1)] = btn

        self.statusBar()

    def status(self):
        action = self.sender()
        btn = action.property("button")
        print('PyQt5 button click')
        self.statusBar().showMessage('{} was pressed with button: {}'.format(action.text(), btn.text()))