I'm trying the add threading in my app write in C++ and QT.
I have a class Framework and one name DeviceMngr.
The framework.h is defined as below:
class Framework : public QObject
{
Q_OBJECT
QThread FrameWorkThread;
public:
Framework();
The framework is initialized by the main. My Main is just doing :
QApplication app(argc, argv);
QThread FrameWorkThread;
Framework *DeviceFramework = new Framework;
DeviceFramework->moveToThread(&FrameWorkThread);
QObject::connect(&FrameWorkThread, SIGNAL(finished()), DeviceFramework, SLOT(deleteLater()));
After, the main in it the main Windows and give the DeviceFramework as argument.
MainUI MyWindows(*DeviceFramework);
MyWindows is discussing with DeviceFramework using Signal/slots.
Framework based is access to an android device using class DeviceMngr and methode.
How is it possible for me to add the DeviceMngr in the same Thread than the Framework.
Can I do something like this in the framework.cpp:
Framework::Framework()
{
Device = new DeviceMngr();
Device->moveToThread(&FrameWorkThread);
}
And the device manager declared as below :
class DeviceMngr : public QObject
{
QThread FrameWorkThread;
public:
DeviceMngr();
~DeviceMngr();
Is this method place the framework and device manager in the FrameWorkThread ?
Thanks Sebastien
It is possible to have your DeviceMngr and Framework instances in the same thread. To do this, you'll need to keep the QThread instance you want to have in common between them in one place (or pass a pointer).
Do you have a reason for not making your DeviceMngr instance a child of Framework? The documentation for QObject says the following about the thread affinity of a child of a QObject instance:
The QObject::moveToThread() function changes the thread affinity for an object and its children (the object cannot be moved if it has a parent).
http://doc.qt.io/qt-5/threads-qobject.html
This would be the simplest way of getting both objects on the FrameWorkThread.
main.cpp
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QThread FrameWorkThread;
Framework *DeviceFramework = new Framework();
DeviceFramework->moveToThread(&FrameWorkThread);
QObject::connect(&FrameWorkThread, SIGNAL(finished()), DeviceFramework, SLOT(deleteLater()));
}
framework.hpp
class Framework : public QObject
{
Q_OBJECT
public:
Framework();
}
framework.cpp
Framework::Framework()
{
Device = new DeviceMngr(this);
}