QWidget::setLayout: 试图设置 QLayout "";在已经有布局的 MainWindow“"上 [英] QWidget::setLayout: Attempting to set QLayout "" on MainWindow "", which already has a layout

查看:64
本文介绍了QWidget::setLayout: 试图设置 QLayout "";在已经有布局的 MainWindow“"上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 PyQt4 中创建一个应用程序,这是我目前的代码:

I'm making an application in PyQt4 and this is my code so far:

import sys
from PyQt4 import QtGui, QtCore

class MainWindow(QtGui.QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.initUi()

    def initUi(self):
        self.setWindowTitle('Main Menu')
        self.setFixedSize(1200, 625)
        self.firstWidgets()
        self.show()

    def firstWidgets(self):
        self.vbox1 = QtGui.QVBoxLayout()
        self.task1 = QtGui.QLabel('Check 1', self)
        self.task1CB = QtGui.QCheckBox(self)
        self.hbox1 = QtGui.QHBoxLayout()
        self.hbox1.addWidget(self.task1)
        self.hbox1.addWidget(self.task1CB)
        self.vbox1.addLayout(self.hbox1)

        self.setLayout(self.vbox1)


def main():
    application = QtGui.QApplication(sys.argv)
    gui = MainWindow()
    sys.exit(application.exec_())

if __name__=='__main__':
    main()

我的问题出在 MainWindow.firstWidgets().我尝试设置布局,但即使这是我第一次为该表单使用 .setLayout ,但出现错误,这让我感到困惑.

My problem is in MainWindow.firstWidgets(). I try to set a layout but I get an error even though that's my first time using .setLayout for that form, which confuses me.

QWidget::setLayout: 试图在 MainWindow "" 上设置 QLayout "",已经有了布局

QWidget::setLayout: Attempting to set QLayout "" on MainWindow "", which already has a layout

推荐答案

您不能直接在 QMainWindow 上设置 QLayout.您需要创建一个 QWidget 并将其设置为 QMainWindow 上的 central widget 并将 QLayout 分配给它.

You can't set a QLayout directly on the QMainWindow. You need to create a QWidget and set it as the central widget on the QMainWindow and assign the QLayout to that.

wid = QtGui.QWidget(self)
self.setCentralWidget(wid)
layout = QtGui.QVBoxLayout()
wid.setLayout(layout)

这篇关于QWidget::setLayout: 试图设置 QLayout "";在已经有布局的 MainWindow“"上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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