Currently, I have a QToolBar
with different checkable actions grouped in QActionGroup
s set to autoExclusive
. This works well.
Now, I would like to have one QAction
with a menu so that user can choose the behavior of this action. So I decided to use a QToolButton
coupled to a QAction
Problem: I found 2 ways to add stuff to QToolBar :
- adding action: it displays action text(beside icon) without toolbutton submenu
- adding toolbutton: does not display action text (only icon) but submenu is shown
Below is an MWE:
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import (QMainWindow, QToolBar, QAction, QApplication, QStyle,
QActionGroup, QToolButton, QMenu)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
# Toolbar definition
self.toolBar = QToolBar(self)
self.toolBar.setIconSize(QSize(24, 24))
self.toolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
self.addToolBar(Qt.TopToolBarArea, self.toolBar)
# Creation of 2 dummy actions
a1 = QAction("My action 1", self)
a2 = QAction("My action 2", self)
# Making actions checkable
a1.setCheckable(True)
a2.setCheckable(True)
# Creating one ToolButton with one default action
tB = QToolButton()
tB.setText("Action 3")
a3 = QAction("Action 3", self)
tB.setDefaultAction(a3)
tB.setCheckable(True)
a3.setCheckable(True)
m = QMenu(tB)
sub_a1 = QAction("sub 1", m)
sub_a2 = QAction("sub 2", m)
sub_a1.setCheckable(True)
sub_a2.setCheckable(True)
m.addActions([sub_a1, sub_a2])
tB.setMenu(m)
tB.setPopupMode(QToolButton.ToolButtonPopupMode.MenuButtonPopup)
# Adding some icon to each action
a1.setIcon(QIcon(QApplication.style().standardIcon(QStyle.StandardPixmap.SP_DirIcon)))
a2.setIcon(QIcon(QApplication.style().standardIcon(QStyle.StandardPixmap.SP_FileIcon)))
a3.setIcon(QIcon(QApplication.style().standardIcon(QStyle.StandardPixmap.SP_FileIcon)))
tB.setIcon(QIcon(QApplication.style().standardIcon(QStyle.StandardPixmap.SP_FileIcon)))
ag = QActionGroup(self)
ag.setExclusive(True)
ag.addAction(a1)
ag.addAction(a2)
ag.addAction(a3)
# Two ways to add things to self.toolBar
self.toolBar.addActions([a1, a2, a3]) # <-- (1) adding a3: displays text "Action 3" (beside icon) without submenu
self.toolBar.addActions([a1, a2]) # <-- (2) adding tB: does not display text "Action 3" (only icon)
self.toolBar.addWidget(tB) # but submenu is shown
if __name__ == '__main__':
app = QApplication([])
mainWindow = MainWindow()
mainWindow.show()
app.exec()