QTimer::singleShot(0, []{/* your code here */});
That's about it, really. Using a 0ms timer means your code will run on the next event loop iteration. If you want to make sure the code won't run if a certain object doesn't exist anymore, provide a context object:
QTimer::singleShot(0, contextObj, []{/* your code here */});
This is well documented.
I used a lambda here just for the example. Obviously you can provide a slot function instead if the code is long.
If you want your code to be executed repeatedly on every event loop iteration instead of just once, then use a normal QTimer that is not in single-shot mode:
auto timer = new QTimer(parent);
connect(timer, &QTimer::timeout, contextObj, []{/* your code here */});
timer->start();
(Note: the interval is 0ms by default if you don't set it, so QTimer::timeout()
is emitted every time events have finished processing.)
Here's where this behavior is documented.
And it goes without saying that if the code that is executed takes too long to complete, your GUI is going to freeze during execution.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…