简体   繁体   中英

Qt thread calculations output to own widgets in GUI?

So basically this program I'm manipulating uses threading in Qt to find all prime numbers within a specified range using a specified number of threads (up to a maximum of 4 threads).

Each thread must output the primes it finds in its own GUI widget of some sort.

I skipped a lot of the basics when coming up with my current code but so far it does everything I mentioned above EXCEPT for outputting the data to widgets and also separating each thread's data into its own widget.

So my question is.. Which widget am I supposed to use for the output for each thread; a text widget/list widget, etc ? And also how does one normally separate each thread's 'calculation' so that I can output each thread to its own widget?

Threads other than the main thread aren't allowed to call methods on GUI widget objects directly, since that wouldn't be thread safe (because the main GUI thread may also be calling methods on the widgets at any time, eg to redraw them when the window size changes).

So instead, your calculation thread(s) need to send a message to the main thread, asking it to update the widget on their behalf.

Usually the easiest way to do that is to have the calculation thread emit a signal containing the data you want to display (eg as a QString), and connect() that signal via a QueuedConnection to the appropriate widget's setText() slot (or to some other appropriate slot that will update the widget).

The other possible way to do it is to have your widget thread call QApplication::postEvent(theTargetWidget, new MyEventType(myResultData)). In this case MyEventType would be your own subclass of QEvent that contains the data you want to send to the main/GUI thread. Then you would make sure that (theTargetWidget) is also a subclass of yours, where you've overridden the "bool event(QEvent *)" method to check for incoming events of MyEventType, extract the data from them, and update the widget with it. Every time your calculation thread called postEvent(), Qt would make sure that event() gets called ASAP in the main/GUI thread.

Once you've got the inter-thread messaging set up safely (via either of the above two methods) then it doesn't matter what type of QWidget you are using to display the results; any type will work. (Conversely, if you don't do the messaging safely, none of Qt's widgets will work reliably, as none of them expect to have their methods called directly by multiple threads)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM