Python PyQt5-如何在工具栏中添加操作菜单?
我想从工具栏中的项目添加菜单。 例如,从以下代码:Python PyQt5-如何在工具栏中添加操作菜单?,python,pyqt,pyqt5,qmenu,qtoolbar,Python,Pyqt,Pyqt5,Qmenu,Qtoolbar,我想从工具栏中的项目添加菜单。 例如,从以下代码: import sys from PyQt5.QtWidgets import QAction, QMainWindow, QApplication class Menu(QMainWindow): def __init__(self): super().__init__() colors = QAction('Colors', self) exitAct = QAction('Exi
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_())
我得到:
我想按“颜色”并获得选项列表(如Qmenu
,但用于工具栏)。
如何实现这一点?如果要将
QMenu
添加到QToolBar
项,则必须添加支持该项的小部件,例如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_())
谢谢你的帮助。如果你也检查一下这个问题,会有很大帮助-