Qt4 Interfacing with the UI thread

和自甴很熟 提交于 2019-12-24 23:17:14

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/13332859/qt4-interfacing-with-the-ui-thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!