import os
import sys
from PyQt5 import QtGui
from PyQt5 import QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
def main():
app = QtWidgets.QApplication(sys.argv)
programWindow = ProgramWindow()
programWindow.show()
sys.exit(app.exec_())
class ProgramWindow(QtWidgets.QMainWindow):
def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.setup_main_window()
self.set_window_layout()
def setup_main_window(self):
self.resize( 800, 600 )
self.setWindowTitle( "Test" )
def set_window_layout(self):
self.startSimulationButton = QPushButton( 'Start Simulation' )
horizontalLayout = QHBoxLayout()
horizontalLayout.addWidget( self.startSimulationButton )
horizontalGroupBox = QGroupBox( "My Group" )
horizontalGroupBox.setLayout( horizontalLayout )
main_vertical_layout = QVBoxLayout()
main_vertical_layout.addWidget( horizontalGroupBox )
self.setLayout( main_vertical_layout )
if __name__ == "__main__":
main()
当我运行它时,它会显示一个空窗口并在控制台上抛出此错误:
QWidget::setLayout: Attempting to set QLayout "" on ProgramWindow "", which already has a layout
我已经查看了QLayout: Attempting to add QLayout "" to QWidget "", which already has a layout,但我不认为我正在做这些,这段代码有什么问题?
注释掉最后一行self.setLayout( main_vertical_layout )
修复了它,但当然,屏幕上没有显示任何内容。
此代码应使用布局QGroupBox
创建QHBoxLayout
,并将QGroupBox
放在布局QVBoxLayout
中。 QVBoxLayout
应附在我的主窗口上:
答案 0 :(得分:1)
用@Aviad说你的代码可能是这样的:
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QPushButton,
QHBoxLayout, QGroupBox, QVBoxLayout)
class ProgramWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.setup_main_window()
self.set_window_layout()
def setup_main_window(self):
self.centralwidget = QWidget()
self.setCentralWidget(self.centralwidget)
self.resize( 800, 600 )
self.setWindowTitle( "Test" )
def set_window_layout(self):
self.startSimulationButton = QPushButton( 'Start Simulation' )
self.horizontalLayout = QHBoxLayout(self.centralwidget)
self.horizontalLayout.addWidget( self.startSimulationButton )
self.horizontalGroupBox = QGroupBox( "My Group" )
self.horizontalLayout.addWidget( self.horizontalGroupBox )
self.main_vertical_layout = QVBoxLayout()
self.horizontalGroupBox.setLayout( self.main_vertical_layout )
button1 = QPushButton( 'Button1' )
button2 = QPushButton( 'Button2' )
self.main_vertical_layout.addStretch(1)
self.main_vertical_layout.addWidget( button1 )
self.main_vertical_layout.addWidget( button2 )
def main():
app = QApplication(sys.argv)
programWindow = ProgramWindow()
programWindow.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
答案 1 :(得分:0)
使用QMainWindow的正确方法是使用“centralWidget”,使用您的布局设置此中央窗口小部件,然后就可以了。 见setCentralWiget