Search code examples
performanceqtqthread

Modify Widgets in non-GUI thread in Qt?


Suppose I have multi-threaded my Application. Then as per Qt philosophy you cannot even modify the properties of Widgets added in GUI. Say an object of class Not_GUI has been moved to another QThread, then it illegal to call button1->SetEnabled(false); (button1 is a QPushButton added in GUI) in a function of Not_GUI.

Currently my application has many GUI widgets (like QLabel, QLineEdit, etc) & since all their events are processed in only 1 thread the application hangs for a while due to the enormous painting activity. Is there a way by which I can somehow distribute some of the workload of Widgets to various thread's?


Solution

  • For the first example use signals and slots. QWidget::setEnabled() is a slot. create a signal modifyWidgetEnableState(bool) and connect to the slot. trigger the signal instead of using the direct method call.

    the application hangs for a while due to the enormous painting activity

    Are these widgets Qt build in? If yes I doubt the hang is due to the painting. Are these widgets yours? Then you may be doing too much processing in your subclassed event handlers. The first thing to do will be to try to improve the performance of whatever you doing, the second thing will be to move the heavy processing in threads, and (again) use signals and slots to communicate with the widgets.

    EDIT: Assume o1 and o2 and are moved to different threads t1 and t2.

    Whenever o2->slot() is executed as a normal function call then it is the calling thread which is executing slot(). Remember, slot() after all is a normal C++ method. Whenever a signal sig() connected to slot() is triggered, then it is the receiver thread which is executing slot(). So choose either one or the other, otherwise you will be subject to race conditions.