Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
985 views
in Technique[技术] by (71.8m points)

qt - Running code in the main loop

I need a way to run an update function of my own in the main thread. I couldn't find a signal that would tick me every time the main loop runs.

Am I doing this wrong ? Is it a Qt thing to force user code to run in threads if we want to run something in a loop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...