Solved QThread movetoThread howto?
-
Dear People of the Internet, I'm realy confused about the usage of QThread.
I got a little class which communicates over a SerialPort with a little robot.
So far so good. Sadly this class needs to wait for the robot to finish with the execution of his task.So i got a small "commincation class"
//conenction Object class SerialConnection: public QObject { Q_OBJECT public: explicit SerialConnection( QObject *parent = 0); virtual ~SerialConnection(); //evil Method which needs alot of time to executed and needs to be threaded int move(QPoint); //other evil Method needs alot of time int concurWorld(bool showMercy); }
I got a main class which calls the "move" and concurWorld methods. Those Methods wont be called at the same time.
All i want to do is to Call those methods in a Thread so it doesnt block my main appplication.
Somehow it should work like thisvoid mainClass::callmove() { QThread * thread = new QThread(); SerialConnection * serial = new SerialConnection(); serial->moveToThread(thread); //at this point I got no clue how to continue }
I know that i need to change the functions to Slots in my serialconnection class and i know that i can connect the start signal of the thread to one of those slots.
But how can i parse some arguments to those methods and how can i get the return values? And how can i connect both of them to a thread when there is only the start singnal of thread?
I feel so dump for asking such a question but the Internet itself seems to be split on deciding which is the right way to use QThreads.Thanks for the help
-
class SerialConnection: public QObject { Q_OBJECT public: explicit SerialConnection( QObject *parent = 0); virtual ~SerialConnection(); signals: void moveReturned(int); void concurWorldReturned(int); public slots: void runMove(QPoint val){emit moveReturned(move(val));} void runConcurWorld(bool val){emit concurWorldReturned(concurWorld(val));} private: //evil Method which needs alot of time to executed and needs to be threaded int move(QPoint); //other evil Method needs alot of time int concurWorld(bool showMercy); }
void mainClass::callmove() { QThread * thread = new QThread(); SerialConnection * serial = new SerialConnection(); serial->moveToThread(thread); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), serial, SLOT(deleteLater())); thread->start(); }
now you can use any signal connected to the 2 new slots to run it (or use QMetaObject::invokeMethod with Qt::QueuedConnection) and when the process is finished the object will emit the signal with the return value
-
Thank you kind Sir! I'll always be in your debt!
Cheers.