PyQt MainWindow不显示小部件


问题内容

我正在用PyQt制作GUI,而MainWindow类却遇到问题。该窗口不显示我在其他类中定义的窗口小部件,或者将在左上角显示一小部分窗口小部件,然后剪切其余窗口小部件。有人可以帮我解决这个问题吗?

这是一些显示我的问题的示例代码。

import sys
from PyQt4 import QtGui, QtCore

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent=parent)
        self.resize(300, 400)
        self.centralWidget = QtGui.QWidget(self)
        self.hbox = QtGui.QHBoxLayout(self.centralWidget)
        self.setLayout(self.hbox)

        names = ['button1', 'button2', 'button3']
        testButtons = buttonFactory(names, parent=self)
        self.hbox.addWidget(testButtons)

class buttonFactory(QtGui.QWidget):
    def __init__(self, names, parent=None):
        super(buttonFactory, self).__init__(parent=parent)
        self.vbox = QtGui.QVBoxLayout()
        self.setLayout(self.vbox)
        for name in names:
            btn = QtGui.QPushButton(name)
            self.vbox.addWidget(btn)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    gui = MainWindow()
    gui.show()
    app.exec_()

问题答案:

QMainWindow具有一个中央窗口小部件,该窗口小部件是一个容器,您应在其中添加窗口小部件。它有自己的布局。QMainWindow的布局用于工具栏等。必须使用setCentralWidget方法设置centralWidget
。仅仅称呼它是不够的self.centralWidget

请改用以下三行。

self.setCentralWidget(QtGui.QWidget(self))
self.hbox = QtGui.QHBoxLayout()
self.centralWidget().setLayout(self.hbox)