我是一名有用的助手,可以为您进行文本翻译。
我有一个Qwidget,通常会在Qmainwindow中显示。有时候只需要使用特定Qwidget的功能,而不需要使用整个mainwindow。如果是这种情况,我希望在我的widget中有一个菜单栏。
我尝试过:
if parent == "self":
self.layout().addMenubar(self)
但是使用上述代码时,代码编译会无错误提示就停止了。 我做错了什么?谢谢!
好的,我可以做到!
您只需在您的QWidget
中添加QtGui.QMenuBar(self)
并像使用QMainWindows
一样实现即可。
参考文献:这里
例子:
import sys
from PyQt4 import QtGui
class QTestWidget (QtGui.QWidget):
def __init__ (self):
super(QTestWidget, self).__init__()
self.myQMenuBar = QtGui.QMenuBar(self)
exitMenu = self.myQMenuBar.addMenu('File')
exitAction = QtGui.QAction('Exit', self)
exitAction.triggered.connect(QtGui.qApp.quit)
exitMenu.addAction(exitAction)
myQApplication = QtGui.QApplication(sys.argv)
myQTestWidget = QTestWidget()
myQTestWidget.show()
myQApplication.exec_()
敬礼,
还有一种很干净的方法可以将 QMainWindow
与 QWidget
结合起来,使用两个类:
import sys
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.win_widget = WinWidget(self)
widget = QtGui.QWidget()
layout = QtGui.QVBoxLayout(widget)
layout.addWidget(self.win_widget)
self.setCentralWidget(widget)
self.statusBar().showMessage('Ready')
self.toolbar = self.addToolBar('Exit')
exitAction = QtGui.QAction ('Exit', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(QtGui.qApp.quit)
self.toolbar = self.addToolBar('Exit')
self.toolbar.addAction(exitAction)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
self.setGeometry(300, 300, 450, 250)
self.setWindowTitle('Test')
self.setWindowIcon (QtGui.QIcon('logo.png'))
self.show()
class WinWidget (QtGui.QWidget) :
def __init__(self, parent):
super (WinWidget , self).__init__(parent)
self.controls()
#self.__layout()
def controls(self):
self.qbtn = QtGui.QPushButton('Quit', self)
self.qbtn.setFixedSize (100,25)
self.qbtn.setToolTip ("quit")
self.qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
self.qbtn.move(50, 50)
def main():
app = QtGui.QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
def menu_bar (self) :
self.menuBar = QtGui.QMenuBar (self)
fileMenu = self.menuBar.addMenu ("File")
self.menuBar.show()
def menu_bar (self) :
self.menuBar = QtGui.QMenuBar (self)
fileMenu = self.menuBar.addMenu ("File")
exitAction = QtGui.QAction(QtGui.QIcon('exit24.png'), 'Exit', self)
fileMenu.addAction(exitAction)
exitAction.triggered.connect(self.close)
exitAction.setShortcut('Ctrl+Q')
self.menuBar.show()
保持使用QMainWindow是个好主意,因为QMenuBar是为在其中使用而设计的。
话虽如此,当我也在研究同样问题时,我发现这篇文章很有帮助:Qt QWidget add menubar
看看它是否可以帮到你。它确实帮了我。