I have a widget that I need to recreate. I have made a massively simplified example below. In the example I want to recreate the widget with new attributes. I know in this example I could use QtGui.QLabel.setText()
, however I can't do the same thing in the real program.
Here is the example:
from PyQt4 import QtGui
import sys
class MainWindow(QtGui.QWidget):
def __init__(self):
super().__init__()
self.initAttributes()
self.initLabel()
self.initUI()
def initAttributes(self):
self.text = 'initial text'
def initLabel(self):
self.label = QtGui.QLabel()
self.label.setText(self.text)
def changeText(self):
self.text = 'different text'
self.initLabel()
self.initUI()
def initUI(self):
button = QtGui.QPushButton()
button.clicked.connect(self.changeText)
grid = QtGui.QGridLayout()
grid.addWidget(self.label)
grid.addWidget(button)
self.setLayout(grid)
self.show()
app = QtGui.QApplication(sys.argv)
window = MainWindow()
app.exec_()
What I'm trying to do here is make a widget that has some initial attributes, in this example a label with text 'initial text'
. As aforementioned, I am not trying to change the attributes, I am trying to recreate the object with new ones taken from attributes belonging to the window object.
The idea behind the button is that when pressed, it will change the window's 'self.text' attribute to something else, and will try to recreate the label, using the same method as before, initLabel
.
The result should be that the window is reinitialized, and the recreated label will have the new text 'different text'
. However, nothing happens.
Edit:
The solution is that setLayout
cannot be called twice for the same widget. When using the widget resetting technique in Schollii's linked answer, it works as it should. Below are the amended, working functions (rather than dumping the whole code again)
def changeText(self):
self.text = 'different text'
self.initLabel()
self.delLayout()
self.initUI()
def delLayout(self):
QtGui.QWidget().setLayout(self.layout())