[PyQt] Any way to run code before each QThread?

Ned Batchelder ned at nedbatchelder.com
Sun Jul 15 16:24:42 BST 2018


On 7/15/18 10:55 AM, 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.
>
>

I've only poked around for ten minutes, but that's what I'm seeing also: 
I could get a signal from a specific thread, but only if I were alerted 
to its creation and could connect the signal.

Anyone have any other hacky^H^H^H^H^Hcreative ideas for how to 
accomplish this? :)

--Ned.


More information about the PyQt mailing list