HOw to use QApplication on a separate thread other than the main thread?
-
Hi all,
I have a main thread and a processing thread. I want to create an instance of QApplication on the processing thread and not on the main thread. How to do this?
Secondly,
If i create widgets on the processing thread would they run as expected?Mainly i want to eliminate the use of QApplication in the main thread. Please suggest me on this.
thanks in advance!
-
A lot of Qt classes (all classes derived from QObject, for example) depend on QCoreApplication istance being present. This is why Q*Application is usually the first line in main routine of Qt applications. You will most probably be unable to create a QThread before the QApplication, so I don't think your scenario is possible (maybe it will work if you use STD threads or Boost threads instead).
The GUI itself should work OK in another thread, though. It is important that all widgets are instantiated in the same thread, but it should not matter whether that thread is the main one.
-
welcome to forum.
You can create the QApplication insider worker thread and start creating UI. I have enclosed sample for this. But I don't suggest this.
How about moving heavy computation itself to worker thread ? This refactoring of this code makes good sense.
-
I feel you should stick standard coding practice of Qt. This kind of code may create kind of confusion for others as code readability.
-
Since it is cross platform app, some platforms may things differently with threads. We need to worry about this as well.
Just as Example
My main(..)
@int main(int argc, char *argv[])
{
WorkerThread thread;
thread.run();
QEventLoop a;
return a.exec();
}void WorkerThread::run(){
qDebug() << "I am here"<< endl;
char* argVV= "Thinks";
int argc = 0;
QApplication *app = new QApplication(argc,&argVV);
QPushButton *button = new QPushButton("Hello");
button->show();
exec();
}@ -
-
@dheerendra god bless you my friend you just saved our school projet.