riyadude
riyadude

Reputation: 347

PyQt: Get menu button object name instead of menu item

I have several qpushbuttons with a menus and am trying to get the specific button that has a menu item selected. Right now using the sender function I am able to get the menu item selected but I require the actual button which holds the menu (button 1 in this case).

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

Upvotes: 0

Views: 1562

Answers (1)

eyllanesc
eyllanesc

Reputation: 244003

A possible solution is to pass the button as a property to each QAction using the setProperty() method, and obtain it in the slot using 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()))

Upvotes: 2

Related Questions