使用 PySide 开发 GUI

Developing a GUI with PySide

我正在尝试在 GUI 应用程序中获取按钮和菜单栏。当我 运行 我的代码时,可以看到带有菜单栏的 GUI,但看不到按钮。这是我的示例代码。并且代码编译没有任何错误。

import sys
from PySide.QtGui import *
from PySide.QtCore import *

class guiwindow(QMainWindow):

    def __init__(self):
        super(guiwindow,self).__init__()

        self.menubar()

    def menubar(self):
        textEdit = QWidget()
        self.setCentralWidget(textEdit)

        exitAction = QAction('Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

        self.statusBar()

        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)

        self.setGeometry(400, 100, 1200, 800)
        self.setWindowTitle("Menubar + Buttons")


        button = QPushButton("Test")
        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(button)
        self.setLayout(hbox)  
        self.show()


def main():
    app = QApplication(sys.argv)
    ex = guiwindow()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

通常,在 GUI 编程中,您必须熟悉 parent 和 child 小部件的概念。如果你想让你的按钮在你的 window 里面,那么后者应该是前者的 child。

所以使用:

button = QPushButton("Test", parent=self)

而不是:

button = QPushButton("Test")

希望对您有所帮助!