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

David Boddie david at boddie.org.uk
Sun Jul 15 15:43:41 BST 2018

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.

At least, it looks simple in principle...


More information about the PyQt mailing list