0

I do use PyQt5 and try to create a toolbar where one of the buttons do have a drop down menu with two entries.

The code below works without exceptions. The button do have its dropdown arrow right of it. But clicking on that arrow has no effect. The menu do not pop up.

enter image description here

#!/usr/bin/env python3
import sys
from PyQt5.QtWidgets import (
    QMainWindow, QApplication, QAction, QStyle, QToolButton, QMenu)


class Window(QMainWindow):
    def __init__(self, parent=None):
        """Initializer."""
        super().__init__(parent)

        # Actions
        ico_one = self.style().standardIcon(QStyle.SP_DirIcon)
        self.act_one = QAction(ico_one, 'one', self)
        self.act_one.triggered.connect(lambda: print('one'))

        ico_sub_one = self.style().standardIcon(QStyle.SP_ArrowBack)
        self.act_sub_one = QAction(ico_sub_one, 'sub one', self)
        self.act_sub_one.triggered.connect(lambda: print('sub-one'))

        ico_two = self.style().standardIcon(QStyle.SP_TrashIcon)
        self.act_two = QAction(ico_two, 'two', self)
        self.act_two.triggered.connect(lambda: print('two'))

        # Toolbar
        toolbar = self.addToolBar('main')

        # Add actions to toolbar
        toolbar.addAction(self.act_one)
        toolbar.addAction(self.act_two)

        # create sub-menu for one toolbarbutton
        wdg_menu = QMenu()
        wdg_menu.addAction(self.act_one)
        wdg_menu.addAction(self.act_sub_one)

        # get toolbar button
        wdg = toolbar.widgetForAction(self.act_one)

        # add sub-menu to it
        wdg.setMenu(wdg_menu)
        wdg.setPopupMode(QToolButton.MenuButtonPopup)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())
buhtz
  • 10,774
  • 18
  • 76
  • 149
  • 1
    From the [`setMenu()` documentation](https://doc.qt.io/qt-5/qtoolbutton.html#setMenu): "[...] Ownership of the menu is **not** transferred to the tool button". Your menu gets garbage collected as soon as `__init__` returns. Change to `QMenu(self)` (or any other valid parent you believe it consistent with the purpose) or at least make it persistent: `self.wdg_menu = QMenu()`. – musicamante Jul 15 '23 at 15:22

0 Answers0