Issue
I want to add a menu from an item in a toolbar. For example, from the following code:
import sys
from PyQt5.QtWidgets import QAction, QMainWindow, QApplication
class Menu(QMainWindow):
def __init__(self):
super().__init__()
colors = QAction('Colors', self)
exitAct = QAction('Exit', self)
self.statusBar()
toolbar = self.addToolBar('Exit')
toolbar.addAction(colors)
toolbar.addAction(exitAct)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
menu = Menu()
sys.exit(app.exec_())
I get:
I want to press on 'Colors' and get a list of options (like Qmenu
, but for the toolbar).
How can I achieve this?
Solution
If you wish to add a QMenu
to a QToolBar
item you must add a widget that supports it, for example a QPushButton
:
import sys
from PyQt5 import QtWidgets
class Menu(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
colorButton = QtWidgets.QPushButton("Colors")
exitAct = QtWidgets.QAction('Exit', self)
toolbar = self.addToolBar("Exit")
toolbar.addWidget(colorButton)
toolbar.addAction(exitAct)
menu = QtWidgets.QMenu()
menu.addAction("red")
menu.addAction("green")
menu.addAction("blue")
colorButton.setMenu(menu)
menu.triggered.connect(lambda action: print(action.text()))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
menu = Menu()
menu.show()
sys.exit(app.exec_())
Answered By - eyllanesc
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.