PyQt MainWindow 不显示小部件 [英] PyQt MainWindow not showing widgets

查看:54
本文介绍了PyQt MainWindow 不显示小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PyQt 制作 GUI,但我的 MainWindow 类有问题.该窗口不显示我在其他类中定义的小部件,或者它会在左上角显示一小部分小部件,然后切断小部件的其余部分.有人可以帮我解决这个问题吗?

I am making a GUI with PyQt, and I am having issues with my MainWindow class. The window doesn't show widgets that I define in other classes, or it will show a small portion of the widgets in the top left corner, then cut off the rest of the widget. Can someone please help me with this issue?

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

Here is some example code showing my issue.

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 的布局用于工具栏等.centralWidget 必须使用 setCentralWidget 方法设置.仅仅称之为 self.centralWidget

A QMainWindow has a central widget that is a container in which you should add your widgets. It has its own layout. The layout of the QMainWindow is for toolbars and such. The centralWidget must be set with the setCentralWidget method. It isn't enough to just call it self.centralWidget

改用以下三行.

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

这篇关于PyQt MainWindow 不显示小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆