Details
Description
The following script shows a layout with a button that should be replaced by a label (with layout.replaceWidget method) when clicked.
from PySide2.QtWidgets import QVBoxLayout, QLabel, QPushButton, QWidget, QApplication app = QApplication() win = QWidget() layout = QVBoxLayout() button = QPushButton("Click to replace") def do_replace(): global layout, button label = QLabel("Replacement") layout.replaceWidget(button, label) button.deleteLater() #label.parentWidget() # Uncomment this line to "fix" the program button.clicked.connect(do_replace) layout.addWidget(button) win.setLayout(layout) win.show() app.exec_()
As is, when the button is clicked, the button disappears but the label doesn't show up. If the comment on line 13 is removed, the program works; which is very strange, because we are only getting a reference to the parent widget of the newly created label, and doing nothing with it.
I guess that, by calling parentWidget, some lazy operation is being forcefully executed and the label shows up, while with the comment, Python deletes the reference to the label variable, and Qt cleans up the label before it gets shown.