我正在尝试对GUI进行一些修改。我的GUI建立在QWidget上。最初,我在QWidget中只有一个QPushButton,然后将其删除并替换为QGridlayout,其中包含许多其他内容。现在,我想首先在QVBoxLayout中保存两个按钮,然后将其删除,然后将QVBoxLayout删除和/或替换为QGridLayout,然后再容纳下一个项目。
问题:我无法使用QGridLayout删除和/或替换QVBosLayout。
下面的最小可重复示例。您需要运行PyQt5
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form():
def __init__(self):
self.nCode_analysis_set_up = QtWidgets.QWidget()
self.nCode_analysis_set_up.resize(300, 100)
self.nCode_analysis_set_up.setWindowFlags(self.nCode_analysis_set_up.windowFlags() | QtCore.Qt.MSWindowsFixedSizeDialogHint)
self.nCode_analysis_set_up.setWindowTitle("nCode analysis set-up")
self.Box = QtWidgets.QVBoxLayout(self.nCode_analysis_set_up)
self.importButton = QtWidgets.QPushButton(self.nCode_analysis_set_up)
self.importButton.setText("Open import model")
self.importButton.clicked.connect(self.input_model)
self.Box.addWidget(self.importButton)
def input_model(self):
self.importButton.deleteLater()
self.Box.deleteLater()
self.Box = QtWidgets.QGridLayout(self.nCode_analysis_set_up)
self.analysis_type_label = QtWidgets.QLabel(self.nCode_analysis_set_up)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
ui = Ui_Form()
ui.nCode_analysis_set_up.show()
sys.exit(app.exec_())
答案 0 :(得分:1)
请勿删除小部件,因为它通常带来的问题多于好处,请使用QStackWidget或QStackedLayout:
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form:
def __init__(self):
self.nCode_analysis_set_up = QtWidgets.QWidget()
self.nCode_analysis_set_up.resize(300, 100)
self.nCode_analysis_set_up.setWindowFlags(
self.nCode_analysis_set_up.windowFlags()
| QtCore.Qt.MSWindowsFixedSizeDialogHint
)
self.nCode_analysis_set_up.setWindowTitle("nCode analysis set-up")
self.stacked = QtWidgets.QStackedLayout(self.nCode_analysis_set_up)
widget1 = QtWidgets.QWidget()
box_1 = QtWidgets.QVBoxLayout(widget1)
self.importButton = QtWidgets.QPushButton()
self.importButton.setText("Open import model")
self.importButton.clicked.connect(self.input_model)
box_1.addWidget(self.importButton)
widget2 = QtWidgets.QWidget()
box_2 = QtWidgets.QGridLayout(widget2)
self.analysis_type_label = QtWidgets.QLabel()
self.analysis_type_label.setText("Label")
box_2.addWidget(self.analysis_type_label)
self.stacked.addWidget(widget1)
self.stacked.addWidget(widget2)
def input_model(self):
self.stacked.setCurrentIndex(1)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
ui = Ui_Form()
ui.nCode_analysis_set_up.show()
sys.exit(app.exec_())