python - 如何在工具栏中添加操作菜单?

标签 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('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_())

我得到:

enter image description here

我想按“颜色”并获取选项列表(如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_())

关于python - 如何在工具栏中添加操作菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51459331/

相关文章:

python - 如何将 OpenCV 图像提供给 Python 中经过训练的 CNN 模型(添加新维度)?

python - lxml 返回空列表

python - QLineEdit 更改 PlaceholderText 颜色

python - pygame.surfarray.pixels3d 没有给出文本表面的正确像素值

python - 将 python 列表作为参数传递给 rpy2 中的 R 函数

python - Pyside(或 PyQt)全局快捷键

python - PySide:如何同时拥有输入掩码和占位符文本

python - PyQt5 不会为 Python 3 安装

python - 如何在PyQt5中使用按键事件

python - PyQt5: Filling in the holes in QPolygon//增加一个qpolygon的大小(高度)