【发布时间】:2021-08-13 19:58:13
【问题描述】:
我正在创建一个自定义工具栏,它会在初始化时自动将自身添加到父级(如果存在)。
我希望这个自定义工具栏不出现在上下文菜单中。然而,尽管使用了setContextMenuPolicy,但与工具栏相关的东西(我不知道是什么)出现了:
我不知道那个上下文菜单项是什么。我的理解是,任何小部件都可以通过其 contextMenuPolicy 添加到上下文菜单中。然而,CustomToolBar 中没有任何其他小部件。
解决方法是在 MainWindow 上完全禁用上下文菜单并创建一个菜单项(例如视图)来切换可见性。
import sys
import time
from PyQt5 import QtCore, QtWidgets
class CustomToolBar(QtWidgets.QToolBar):
def __init__(self, parent=None):
super().__init__(parent=parent)
if parent:
self.setParent(parent)
self.parent().addToolBar(QtCore.Qt.BottomToolBarArea, self)
self.setObjectName('Custom ToolBar')
self.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.counter = 0
self.resize(250, 75)
self.init_widgets()
self.init_layout()
def init_widgets(self):
self.exit_action = QtWidgets.QAction('&Exit', self)
self.exit_action.setShortcut('Ctrl+Q')
self.exit_action.setToolTip('Exit application')
self.exit_action.triggered.connect(self.close)
self.menu = self.menuBar()
self.menu_file = self.menu.addMenu('&File')
self.menu_file.addAction(self.exit_action)
# setting parent to self embeds the custom toolbar in the main window
self.status = CustomToolBar(self)
def init_layout(self):
layout = QtWidgets.QVBoxLayout()
centralWidget = QtWidgets.QWidget()
centralWidget.setLayout(layout)
self.setCentralWidget(centralWidget)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
main_window = MainWindow()
main_window.show()
sys.exit(app.exec_())
【问题讨论】: