如何在QWidget中添加菜单栏?
我有一个Qwidget,通常是在一个Qmainwindow里显示的。有时候其实不需要用整个主窗口,因为我只想用某个Qwidget里的功能。如果是这种情况,我想在我的widget里加一个菜单栏。
我试过这样做:
if parent == "self":
self.layout().addMenubar(self)
但是用上面的代码后,它就停止编译了,也没有报任何错误。我哪里做错了呢?谢谢!
4 个回答
1
继续使用QMainWindow是个好主意,因为QMenuBar就是为了在这个窗口里使用而设计的。
不过,我发现这篇文章对我也很有帮助,当时我也在寻找类似的解决方案: Qt QWidget添加菜单栏
看看这是否能帮助到你。对我来说是有用的。
4
这个可以用:
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()
6
还有一种很简单的方法,可以把 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()
10
好的,我可以做到!
你只需要在你的 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_()
祝好,