Python QWidget::setLayout:正在尝试设置QLayout“&引用;“在主窗口上”&引用;,它已经有了一个布局
我正在用PyQt4制作一个应用程序,这是我目前的代码:Python QWidget::setLayout:正在尝试设置QLayout“&引用;“在主窗口上”&引用;,它已经有了一个布局,python,pyqt4,Python,Pyqt4,我正在用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(
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
,这让我很困惑
QWidget::setLayout:正在尝试在MainWindow“”上设置QLayout“”,
它已经有了一个布局
不能直接在
qmain窗口上设置QLayout
。您需要创建一个QWidget
,并将其设置为QMainWindow
上的中心小部件,并将QLayout
分配给该小部件
wid = QtGui.QWidget(self)
self.setCentralWidget(wid)
layout = QtGui.QVBoxLayout()
wid.setLayout(layout)
只是更新布伦登·阿贝尔的答案:
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()
啊,这与我的MainWindow类继承QMainWindow而不是QtGui.QWidget有关吗?似乎在QMainWindow中获取菜单栏的唯一方法是继承QtGui.MainWindow。是的,您可能希望继承自QMainWindow
,因为它是唯一一个看起来和功能都像应用程序窗口的类。它只是不接受布局。