How can I tell when a PyQt application is idle?

I would like to know when my application is idle in order to preload some content. Does PyQt have an event or something similar?

(I could do it with streams as well, but that seems too complicated.)

+1


a source to share


2 answers


You have at least two different options, you can use a stream or use a timer. The Qt class QThread provides a priority property that you can configure to be processed only when no other threads are running, including the GUI thread. Another option is a one-shot timer. QTimer with a timeout of 0 milliseconds places the event at the end of the event queue so that any events and synchronous functions already active or scheduled will be processed first.

In the code, both parameters look like this:

// (1) use idle thread processing
MyQThreadSubclass idleThread;
idleThread.run(QThread::IdlePriority);

// (2) use QTimer::singleShot
QTimer::singleShot(0, receiver, SLOT(doIdleProcessingChunk));

      

If you go with a single shot of QTimer, be careful how much processing you do as you can still block the Gui. You probably want to break it down into chunks so that the GUI doesn't start to lag behind:



// slot
void doIdleProcessingChunk() {
    /* ... main processing here ... */
    if (chunksRemain())
        QTimer::singleShot(0, receiver, SLOT(doIdleProcessingChunk));
}

      

Obviously this is C ++ syntax, but for PyQt's answer use a single shot timer. In Python, the global interpreter blocker is basically going to make most of your concurrency meaningless if the implementation being called is executed in Python.

You also have the choice of using Python streams or Qt streams, both of which are good for different reasons.

+3


a source


Have a look at QAbstractEventDispatcher . But ... I still suggest using a stream. Causes:

  • It will be portable
  • If you make a mistake in your code, the event loop will be broken -> Application may hang, terminate abruptly, etc.
  • While preloading is in progress, your application hangs. No events will be handled unless you can preload the content one at a time, they are all very small, it only takes a few milliseconds to load, etc.


Use a stream and send a signal to the main stream when the content is ready. It's much easier.

+1


a source







All Articles