class window25(QtWidgets.QMainWindow):
def __init__(self):
try:
super(window25,self).__init__()
self.lineedit=QtWidgets.QLineEdit()
self.checkbox=QtWidgets.QCheckBox()
self.optBox=QtWidgets.QRadioButton()
self.btn=QtWidgets.QPushButton("press me")
self.guichange()
self.btn.clicked.connect(self.guichange)
self.show()
except Exception as E:
print(E)
def guichange(self):
try:
wid=QtWidgets.QWidget()
# self.setCentralWidget()
myLayout=QtWidgets.QVBoxLayout()
myLayout.addWidget(self.btn)
myLayout.addWidget(random.choice([self.lineedit,self.checkbox,self.optBox]))
wid.setLayout(myLayout)
self.setCentralWidget(wid)
except Exception as E:
print(E)
app=QtWidgets.QApplication([])
ex=window25()
sys.exit(app.exec_())
我想做的是实验。不过我知道QStackedWidget可以更改窗口,但我尝试了其他方法,即按一个按钮随机更改主窗口中心小工具。之后有几次成功(即按下按钮3、4次都能正常工作),但之后我遇到了一个错误
wrapped c/c++ object of type QCheckBox has been deleted
wrapped c/c++ object of type QLineEdit has been deleted
我无法理解是哪个语句导致了这个错误,以及为什么我错了或者哪里错了
这是由Qt的实现和原理引起的,回顾观察到的documentation:
正如他所说,如果父控件也破坏了子控件,并且由于所有小部件都有
QObject
作为它们的前身,它们也会遵守这些规则。在但为什么有些小部件会被销毁?
每次使用
setCentralWidget()
时,以前作为中心小部件的对象将被删除。在CentralWidget()的子级是什么?
当小部件附加到布局时,这些小部件被设置为使用该布局的小部件的父级。在
为什么QPushButton没有被消除?
使用
^{pr2}$QPushButton
和其他小部件的情况是,在使用setCentralWidget()
(即删除父对象)之前,它会从父窗口更改:最后,我将使用以下代码解释一个随机示例:
说明:
如果您想交换小部件,适当的选项是
QStackedWidget
,如下所示:相关问题 更多 >
编程相关推荐