I would like to create a widget in asynchronously and then assign it to a dialog in the main thread. I have a functions to create the widget:
shared_ptr<QTableWidget> createTable() {
auto table = make_shared<QTableWidget>()
// ... add some items to the table
return table;
}
When I call this function synchronously everything works as expected. Problem is when I call this function asynchronously:
auto futureWidget = QtConcurrent::run(createWidget);
I use QFutureWatcher::finished() signal and when the widget creation is done, I try to add that widget to the dialog in the main/GUI thread.
The problem is that sometimes it just crashes with SIGSEG when I add an item to the table. Sometimes when it completes the created widget is not shown. Also there is a lot of warnings on the standard output about using pixmap outside GUI thread.
Is that not possible to create widgets in different thread in Qt? If it is possible, how to do it?
No, it is only possible to create GUI widgets within the main thread.
Usually, it does not take much time to create GUI part of widget. If you have some operation, that takes a lot of time, you probably should extract it from process of widget creation, process it in separate thread and then pass result of this operation to the newly created widget.
EDIT
If you have some complex tables in the widget, you should use Qt MVC system, i.e.
QTableViewand model based onQAbstractTableModel. You can then fill model in another thread and only then assign it to view, created in main thread.