繁体   English   中英

PyQt5-如何在工具栏中添加动作菜单?

[英]PyQt5 - How to add actions menu in a toolbar?

我想从工具栏中的项目添加菜单。 例如,从以下代码中:

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 ,但用于工具栏)。 我该如何实现?

如果您希望将添加QMenuQToolBar项目必须添加支持它,例如一个widget 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_())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM