使QToolBar项目具有ContextMenu

时间:2019-04-06 02:21:41

标签: python pyside

如何为我的QToolBar中的项目添加上下文菜单。使用上下文菜单的原因是,我想为每个操作提供一个右键单击>删除操作。类似于Chrome浏览器从书签工具栏中删除书签的功能。我如何在Pyside中实现这一目标?

enter image description here

import os, sys
from PySide import QtGui, QtCore

class Example(QtGui.QMainWindow):
    def __init__(self):
        super(Example, self).__init__()
        self.resize(300,200)
        self.createToolBars()
        self.createActions()


    def createToolBars(self):
        self.toolBar = self.addToolBar('Presets')
        self.toolBar.setIconSize(QtCore.QSize(16,16))
        self.toolBar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)

    def createActions(self):
        self.toolBar.clear()

        presets = ['Abby','Kevin','Bob','Mary']
        for x in presets:
            act = QtGui.QAction(x, self)
            act.setData(x)
            self.toolBar.addAction(act)


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())       

1 个答案:

答案 0 :(得分:2)

您必须实现自定义QToolBar并实现contextMenuEvent方法:

import os
import sys
from PySide import QtCore, QtGui

class ToolBar(QtGui.QToolBar):
    def contextMenuEvent(self, event):
        current_action = self.actionAt(event.pos())
        if current_action is None:
            return
        menu = QtGui.QMenu()
        delete_action  = menu.addAction("delete")
        action = menu.exec_(event.globalPos())
        if action == delete_action:
            self.removeAction(current_action)

class Example(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Example, self).__init__(parent)
        self.resize(300,200)
        self.createToolBars()
        self.createActions()

    def createToolBars(self):
        self.tool_bar = ToolBar('Presets', self)
        self.addToolBar(self.tool_bar)
        self.tool_bar.setIconSize(QtCore.QSize(16,16))
        self.tool_bar.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)

    def createActions(self):
        self.tool_bar.clear()
        presets = ['Abby','Kevin','Bob','Mary']
        for x in presets:
            act = QtGui.QAction(x, self)
            act.setData(x)
            self.tool_bar.addAction(act)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())