QApplication was not created in the main() thread
-
Hello everyone,
Could someone explain why in the following scenario some buggy behavior is present(QTextEdit window is not automatycally updated):@
#include <qapplication.h>
#include <qtextedit.h>
#include <qrunnable.h>
#include <qthread.h>
#include <qthreadpool.h>int main(int argc, char *argv[])
{
class GUIinThread : public QRunnable
{
void run()
{
int argc = 1;QByteArray argvStr = QString("").toLatin1();
char* argv = argvStr.data();QApplication a(argc, &argv);
QTextEdit textEdit;
textEdit.show();a.exec();
}
};GUIinThread *createGUI = new GUIinThread();
QThreadPool::globalInstance()->setExpiryTimeout(-1);
QThreadPool::globalInstance()->start(createGUI);while(true); // prevent main() from return
return 0;-
}@And why is this so important to create QApplication in the main thread?
I'm using Qt5.1.1 under WIn7
Thnaks in advance! -
Hi, QApplication and all other QWidget can only be used in main thread.
http://qt-project.org/doc/qt-5.1/qtcore/threads-qobject.html
-
Hi, 1+1=2,
Thanks for the reply, but I still don't get whats so special about main thread and why we can't have another thread devoted to GUI other than main as long as we don't make any cross-thread gui interactions? -
Some platforms restrict GUI interactions to the first thread spawned by a process: http://www.dribin.org/dave/blog/archives/2009/02/01/main_thread_apis/
Qt is a cross-platform library, and thus it needs to follow the platforms' rules.
-
JKSH,
Thanks, it's finally starting to make sense. That OS X must be a really "fun" thing to deal with... Too bad it has such a frustrating influence on Qt...I have a console app that makes a lot of computation in it's main() and log iteration data to a file, i wanted to log into quickly made fully responsible gui running in parallel to main() so it would be a little change to main() but faced this limitation :(
-
You're welcome. Yea, creating a cross-platform library is hard work. But I think the benefits outweigh the downsides :)
Hmm... could you rename your current main() into something else, and just call it from another thread? You can create a new main(), create your GUI, and start a new thread to run the old main().
P.S. See http://doc-snapshot.qt-project.org/qt5-stable/threads-technologies.html for a comparison of different ways to use threads in Qt. QRunnable is not suitable for permanent threads.
-
Thats a bunch of usfefull links you've got :) (not really too easy to find them on your own)
Ive been stepping into Qt source all morning but was unable to find the difference to QEventDispatcherWin32 if created not on the main thread...
So I guess Im gonna have to go with your suggestion of renaming my main() etc...
Thanks again :) -
You're welcome :) All the best!
(I actually found the first link after reading your post, by searching "GUI main thread" in Google)