Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
928 views
in Technique[技术] by (71.8m points)

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

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()

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: Attempting to set QLayout "" on MainWindow "", which already has a layout

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...