Important: Please read the Qt Code of Conduct -

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) :
        ui(new Ui::qthreads)
        modclient *h=new modclient;
        ccd2 *ccd=new ccd2;

    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?

  • @MartinChan

    try to copy the example from the link below.

    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?

  • Moderators


    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 - child QObject 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.

Log in to reply