我正在使用PyQT编写一个小应用程序。我试图在应用程序顶部创建一个包含常见选项(“文件”,“编辑”,“选项”等)的菜单栏,但是当我尝试将其添加到我的QMainWindow类时,我的工具栏没有出现。我已经查看了周围,但我不知道我做错了什么。请注意,我已经尝试使用
QMainWindow.menuBar()
方法而不是创建 QToolbar
,但如果我这样做,则整个栏都不可见。使用下面的代码,即使它是空的,我至少得到了一个空栏。下面的代码是这个问题的最小示例。我想知道我必须更改什么才能显示操作。import sys
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QBrush
from PyQt5.QtWidgets import QMainWindow, QGraphicsScene, QToolBar, QMenu, QAction, QGraphicsView, QApplication
class GraphWindow(QMainWindow):
def __init__(self):
super().__init__()
self.scene = QGraphicsScene()
# a grid foreground
self.scene.setBackgroundBrush(QBrush(Qt.lightGray, Qt.CrossPattern))
self.grid = True
# Create upper toolbar with menu options
tb = QToolBar()
menu = QMenu()
db_action = QAction("Open file")
db_action.setStatusTip("Select a file to use as a database")
db_action.triggered.connect(self.open_new_db)
menu.addAction(db_action)
tb.addWidget(menu)
tb.setAllowedAreas(Qt.TopToolBarArea)
tb.setFloatable(False)
tb.setMovable(False)
self.addToolBar(tb)
self.statusBar().showMessage("Ready")
# Demonstrate the results from the input.
graphics = QGraphicsView(self.scene)
self.setCentralWidget(graphics)
self.showFullScreen()
def open_new_db(self):
pass
def keyPressEvent(self, e):
# Currently, we respond to a press of the Escape key by closing the program.
if e.key() == Qt.Key_Escape:
self.close()
app = QApplication(sys.argv)
gr = GraphWindow()
sys.exit(app.exec_())