In my Application, I have a QWidget MyWidget
which I need to construct after a PushButton click. Now, MyWidget is a heavy widget with many children components and those children components have many components too. Now, when I try to construct the widget after the push button press, it takes sometimes for the widget to appear, which I don't like. So, I need to construct the widget before the PushButton clicked and keep an instance ready at hand. Thread seems perfect for this job. But I have little idea about Qt Thread.
Now can somebody suggest me how to approach the problem and what can be done to solve the problem?
Note: To say explicitly why is my widget so heavy, in MyWidget, I have 7*24 widgets, each having a stacked Widget with two widgets stacked on it each having a button.
Qt does not support creation of widgets in non-gui threads. The reason is simple: widget constructors are free to access thread-unsafe APIs that can be used by the main thread at any time. Thus even if it might appear to work, it's really a bug in your code if you do it.
Generally speaking, in your heavyweight widget classes, parallelize the non-graphical, long-running initialization tasks. You can use QtConcurrent::run
for this purpose. Of course you need to make your implementation thread-safe for this purpose.
You must also ensure that you absolutely, positively don't use any blocking APIs in your widget code. No GUI code generally, but no widget constructor specifically, should ever:
wait for any file accesses to finish,
wait for any networking to finish,
wait for any database access to finish,
use any waitForXxxx
methods in Qt,
use things that may indirectly access the file system, such as QSettings
.