Can Signal Handlers Memory Leak In Pyqt?
Solution 1:
It is possible to have a memory leak with this design. You need to disconnect the signals and slots if those connections contain references which are keeping objects alive.
Whether or not this actually happens depends on what exactly right_handler
is. If right_handler
is a closure with a reference to self
then you have this problem.
Solution 2:
but in Python I cannot explicitly call the destructor,
You can call destructor in python. Check del and __del__
Do I need to remove the handler to prevent right_objects memory-leaking,
No, you don't need to do that. python will handle that. Run below code check your self.
In this code signal of startButton1
and stopButton1
are connected to methods of class object of Hello
and this object(hello1
) is attribute of Widget class. So hello1
will live until life object of Widget
OR we delete it in method Widget.onDelete
with Delete
button. Once you click Delete
button, destructor of hello1
is called and it will goes out of scope. Now signal of startButton1
and stopButton1
don't work as before.
Now in second row there are buttons startButton2
and stopButton2
, whose signal are connected with object of hello2
. But as soon as construct of Widget
is over hello2
life time is finish. So there is not slot connected for signal of those buttons after Widget
construct is over.
from PyQt5.QtWidgets import QApplication,QPushButton,QWidget,QHBoxLayout,QVBoxLayout
classHello():
def__init__(self):
print("init")
defonStart(self):
print("onStart");
defonStop(self):
print("onStop");
def__del__(self):
print("del")
classWidget(QWidget):
def__init__(self,parent=None):
QWidget.__init__(self,parent);
vLayout = QVBoxLayout()
self.setLayout(vLayout)
buttons1 = QWidget()
hLayout1 = QHBoxLayout()
buttons1.setLayout(hLayout1)
vLayout.addWidget(buttons1)
startButton1 = QPushButton("Start");
stopButton1 = QPushButton("Stop");
deleteButton1 = QPushButton("Delete");
self.hello1 = Hello();
startButton1.clicked.connect(self.hello1.onStart)
stopButton1.clicked.connect(self.hello1.onStop)
deleteButton1.clicked.connect(self.onDelete)
hLayout1.addWidget(startButton1);
hLayout1.addWidget(stopButton1);
hLayout1.addWidget(deleteButton1);
buttons2 = QWidget()
hLayout2 = QHBoxLayout()
buttons2.setLayout(hLayout2)
vLayout.addWidget(buttons2)
startButton2 = QPushButton("Start");
stopButton2 = QPushButton("Stop");
deleteButton = QPushButton("Delete");
hello2 = Hello();
startButton2.clicked.connect(hello2.onStart)
stopButton2.clicked.connect(hello2.onStop)
hLayout2.addWidget(startButton2);
hLayout2.addWidget(stopButton2);
defonDelete(self):
ifhasattr(self,"hello1"):
del self.hello1
app = QApplication([])
w = Widget();
w.show()
app.exec_()
Hope this will clear you doubt.
Post a Comment for "Can Signal Handlers Memory Leak In Pyqt?"