About the right way to use QThread:error:Cannot create children for a parent that is in a different thread.
-
I am trying to write a program about using two approach switches to control two cameras to work.I tried to use a multi-thread struct:the first thread is the ui. class(main thread),the second is the modbus reading thread which can read in the information and the third thread is to control which camera to work.
SO when I tried the singal-slots way to do the work like this:
qthreads::qthreads(QWidget *parent) : QMainWindow(parent), ui(new Ui::qthreads) { ui->setupUi(this); modclient *h=new modclient; ccd2 *ccd=new ccd2; h->moveToThread(&THREAD_Get_Modbus); ccd->moveToThread(&THREAD_Get_Frame); connect(&THREAD_Get_Modbus,&QThread::finished,h,&QObject::deleteLater); connect(&THREAD_Get_Frame,&QThread::finished,ccd,&QObject::deleteLater); connect(ui->pushButton,SIGNAL(clicked(bool)),h,SLOT(connecttoModbusServer())); connect(h,SIGNAL(finishedreading(CAM)),ccd,SLOT(getframe(CAM))); THREAD_Get_Frame.start(); THREAD_Get_Modbus.start(); }
When i start my program,it always reminds me of "QObject: Cannot create children for a parent that is in a different thread.
(Parent is QModbusTcpClient(0x1498298), parent's thread is QThread(0x1452c30), current thread is QThread(0x12ff88c)".So,what's wrong with my code?Is there possible to use three or more threads in Qt?
-
try to copy the example from the link below.
https://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/
don't include a while loop inside your thread as it will block and your application will be unresponsive use a timer if you want to poll data from other threads.
-
@rafael thx first and you said don't use a while loop in my thread,however the thread I created is used to scan the input so I have to use a 'infinite long' loop to read back the input. So I must change while loop to another kind of loop?
-
@MartinChan
Hi,So,what's wrong with my code?
Most probably, you have children objects created in the constructor of your worker object. So Qt's complaining when you invoke
QObject::moveToThread()
. You should fix that - childQObject
instances and their parent can't have different thread affinity.Is there possible to use three or more threads in Qt?
As many as you wish (and as many the OS will allow). The problem here is not with the threads, but how you use them.
Kind regards.