QWidget::setLayout:正在尝试在已具有布局的MainWindow“”上设置QLayout“”

2024-05-21 04:41:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用PyQt4制作一个应用程序,这是我目前的代码:

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

我的问题在{}。我试图设置一个布局,但我得到了一个错误,即使这是我第一次使用.setLayout作为该表单,这让我感到困惑

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


Tags: importselfinitmaindefsyspyqt4task1
3条回答

只是更新布伦登·阿贝尔的答案:

QWidget和QVBoxLayout(对于Python3,PyQt5)现在包含在PyQt5.qtwidts模块中,而不是PyQt5.QtGui模块中

因此,更新代码:

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

这是一个使用PyQt5的示例

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QPushButton, QWidget


class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        self.setWindowTitle('My App')
        
        # Cannot set QxxLayout directly on the QMainWindow
        # Need to create a QWidget and set it as the central widget
        widget = QWidget()
        layout = QVBoxLayout()
        b1 = QPushButton('Red'   ); b1.setStyleSheet("background-color: red;")
        b2 = QPushButton('Blue'  ); b2.setStyleSheet("background-color: blue;")
        b3 = QPushButton('Yellow'); b3.setStyleSheet("background-color: yellow;")
        layout.addWidget(b1)
        layout.addWidget(b2)
        layout.addWidget(b3)
            
        widget.setLayout(layout)
        self.setCentralWidget(widget)


def main():
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

不能直接在QMainWindow上设置QLayout。您需要创建一个QWidget,并将其设置为QMainWindow上的中心小部件,然后将QLayout分配给该小部件

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

相关问题 更多 >