Important: Please read the Qt Code of Conduct -

QSerialPort and QThread

  • I have the main MainWindow class that has instances of the class QThread and another is in charge of communications through the serial port. In the main class I initialize instances in .h as :

    Communications * com ;
    QThread * thread ;

    And in the constructor of the main class .cpp the initialize :

    com = new Comunications();
    thread = new QThread(this);

    I shake my communications class I created the thread above with
    com- > moveToThread (thread) ;

    Also in this class i have the connections of signals and slots.
    When I go to write to the serial port jumps me an error:

    " QObject : Can not create children for a parent That is in a different thread. "

    Can someone help me??

  • yeah, happend to me too.
    the thing is, the any QObject 'knows' who are his childred, so the QSerialPort is alreay listed at the thread that created it, and you are trying to change it.
    try reordering the calls. first moveToThread(), then com = new Comunications();

  • Lifetime Qt Champion


    @yoavmil Are you trying to suggest to call moveToThread on an unallocated object ?

    @Sergio I guess your Communications class contains a QSerialPort ? If so, did you give a parent to your QSerialPort instance (i.e. _serialPort = new QSerialPort(this))? From the error message, probably not, hence it's not moved along with your Communications instance.

  • @Sergio

    To follow up on what @SGaist said, what I normally do is not to create the serial port in the constructor of the Comunications class (assuming you do), but connect a slot in Communications to the QThread::started() signal, and in there create the serial port. That would ensure that when the serial port class is created that it will be created in the thread that needs to use it.

    class Comunications : public QObject {
    public slots:
        void threadStarted() { 
            d_serialPort = new QSerialPort();
            // ... <- set up
        void threadStopped() { 
            d_serialPort.close(); // Might not work/be needed
            delete d_serialPort;
            d_serialPort = nullptr;
        QSerialPort* d_serialPort;

    and then in your constructor

    com = new Comunications();
    thread = new QThread(this);
    connect(thread, &QThread::started, com, &Comunications::threadStarted);

    As @SGaist pointed out, make sure to clean up objects created:

    connect(thread, &QThread::finished, com, &Comunications::threadStopped);

    PS: Please put your code into code blocks when creating posts
    [edit: added example code for cleanup]

  • Lifetime Qt Champion

    @TheBadger Do you also delete it when your thread stops ? Otherwise you have a memory leak here

  • @SGaist

    you also delete...

    Yes definitely, I did not add that part but it should be deleted, will add a possible snippet to the code above, thanks

Log in to reply