[PyQt] Any way to run code before each QThread?
Chris Pezley
chris at pezley.net
Mon Jul 16 12:52:38 BST 2018
You can track all instances of a class in python by creating a cache
which is populated when __new__ is called:
import weakref
from PyQt5 import QtCore, QtWidgets
class MyQThread(QtCore.QThread):
_instances = weakref.WeakSet()
def __new__(cls, *args, **kwargs):
obj = super(MyQThread, cls).__new__(cls, *args, **kwargs)
cls._instances.add(obj)
return obj
def main():
app = QtWidgets.QApplication([])
thread_1 = MyQThread()
thread_2 = MyQThread()
thread_3 = MyQThread()
print(list(MyQThread._instances))
if __name__ == '__main__':
main()
On 07/15/2018 04:55 PM, Florian Bruhin wrote:
> On Sun, Jul 15, 2018 at 04:43:41PM +0200, David Boddie wrote:
>> On Sun Jul 15 12:30:55 BST 2018, Ned Batchelder wrote:
>>
>>> I maintain coverage.py. I have an issue
>>> (https://github.com/nedbat/coveragepy/issues/582) that the code running
>>> in QThreads aren't measured. For the stdlib threading module, I have
>>> code that runs as each thread is created to start the measurement. Is
>>> there any way to do the same for QThreads?
>> Perhaps. See below.
>>
>>> The stdlib feature is threading.settrace
>>> (https://docs.python.org/3/library/threading.html#threading.settrace). I
>>> didn't see anything similar for QThreads, or any other hook that would
>>> give me control before the thread starts running. Am I overlooking
>>> something?
>> From the threading.settrace docs:
>>
>> "Set a trace function for all threads started from the threading module.
>> The func will be passed to sys.settrace() for each thread, before its run()
>> method is called."
>>
>> The QThread.started signal docs (https://doc.qt.io/qt-5/qthread.html#started)
>> say this:
>>
>> "This signal is emitted from the associated thread when it starts executing,
>> before the run() function is called."
>>
>> So it looks like almost exactly what you want. Connect this signal to a slot
>> (function/method) and perform the same setup there.
> That's only for a given QThread instance though - it'd probably work if
> you could somehow find out about all QThread instances created in a
> project, but I can't think of a good way to do that.
>
> Florian
>
More information about the PyQt
mailing list