简体   繁体   中英

Qt4 Interfacing with the UI thread

I have a CLI application that I'm expanding to have a user interface to aid in, well, usability, and am using Qt-4.8.3.

The application connects to an IRC server, and each connection resides in its own thread receiving data. A parser, running in a different thread, then processes the data and reacts accordingly - creating a channel, adding a user, etc.

I've been looking through the documentation and just can't decide (or really see) what would be the most useful method to update the UI in my instance - should I create a class inheriting from QThread and run that, do some trickery with QFuture and QtConcurrent, create a custom struct and pass it populated to the UI thread, use a customEvent(), or is there a better way overall? Code legibility and performance are top requirements.

The code I have at the moment runs perfectly, but naturally creating a new QWidget inside the parser thread instantly breaks with the notification that it's not the UI thread.

There is only a single class (at the moment, which inherits QObject and provides signals + slots capability) that I'm using to run exec on the QApplication, and also holds the creation functions for the server, channel, user, etc.

I can post some code if needed, but there's a lot of it, and I'm not sure it would really be relevant.

The canonical way of doing this is to create QObject/QThread pairs (or multiple QObjects and a single QThread, if you want multiple functions to run in the same thread.) Instead of subclassing QThread, you subclass QObject, create a QThread and move your QObject subclass instance to that thread with moveToThread() . The intended use of QThread is as an interface to the operating system's threading functionality, not as a container that runs your code. (See http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation ).

All communication with the GUI has of course to happen using signals and slots.

This situation sounds pretty common. It is just the basic solution to forwarding processed data up from threads to the main thread for UI updates.

The easiest way to do it is to just make use of the SIGNAL/SLOT mechanism. Your main thread should be connected to signals from your parser. When data is ready in your parser, just emit a signal with the data structure that you choose to use. The data structure is simply whatever suits your needs for communicating the data. Just a struct or whatever you want.

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