Unsolved background thread before main loop starts
-
i need to call a function periodically and thus i don't want it to be in main (gui) thread.
the problem here is that the whole app initialization process is being done beforeapp.exec()
and when i create aQObject
subclass object i need some of the initialization results. when i move the object to the background thread, then start the thread and call the object's function, the main loop hasn't started yet and thus the function doesn't get executed.so i'm giving up on relying on qt's mechanisms.
since i need to call the function periodically, i need something like a timer, and a thread to run object's function in. please give me ideas what to do
-
Hi
but why is it a issue that exec() runs ?
Else it will be difficult to send any result back to the main app.You dont have so show mainwindow before exec().
So there is no issue to run thread and get result, and then display what ever main gui does. -
@mrjj when i create the object before exec() (no new thread created), and call a method on it that prints something, nothing gets printed.
-
@user4592357
Are you sure you actually moveToThread correctly ?
Anyway, if exec() is not running threads cannot report anything back to
main as no signals will work.Why cant you just wait to show something until its ready ?
-
@mrjj i wanna understand: in what loop is thread gonna be created if there's no main loop???
and i can't wait for exec() cause i do a lot of post-app-working job before exec() (like connecting to the server, checking some information from there etc). there i create some handles that are needed to be passed to the new thread (not moved, just a pointer pass)...
-
@user4592357
I have never tried it with no exec() running
If you need tread to report back to some object in main thread , you need exec()the default run() of qthread calls event loop. so it has its own loop.
http://doc.qt.io/archives/qt-4.8/qthread.html#runIm not sure why u can just let exec() run and when thread report back,
then do show() for mainwindow or what ever is needed.Can you show your thread code?
-
class Worker : public QObject { Q_OBJECT public: explicit Worker(int param= 300) : m_param(param) { emit initialized(); } void start(HANDLE *handle) const { // call the funcion periodically } signals: void initialized() const; private: int m_param; };
auto pBgThread = new QThread; pBgThread->setPriority(QThread::LowPriority); Worker o; o.moveToThread(pBgThread); QObject::connect(pBgThread, SIGNAL(finished()), &o, SLOT(deleteLater())); QObject::connect(pBgThread, SIGNAL(finished()), pBgThread, SLOT(deleteLater())); o.start(handle); pBgThread->start();