QObject: Cannot create children for a parent that is in a different thread.



  • I want to open the listen method in a different thread, it shows that it's listening but I can't connect to the server side not from client nor from telnet. I googled and found that I have to use SLOT/SIGNAL mechanism but don't understand use it for what?

    Start Thread for listening:

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        for(int i=0;i<4;i++){
            socketC = new TCPSocket;
            connect(this,SIGNAL(startThread()),socketC,SLOT(StartThread()));
           // connect(socketC,SIGNAL(sendImage(QImage&)),this,SLOT(recImg(QImage&)));
            connect(socketC,SIGNAL(msg(QString)),this,SLOT(Log(QString)));
            connect(socketC,SIGNAL(users(QString)),this,SLOT(Users(QString)));
            connect(socketC,SIGNAL(idDisconnected(int)),SLOT(UpdateList(int)));
            port_struct = new PORT_;
            port_struct->locked = true;
            socketC->setPORT(DEFAULT_PORT+i);
            socketC->setId(i);
            SocketInst.push_back(socketC);
            PORTS_NUM.push_back(port_struct);
            //SocketInst.at(i)->start();
            emit startThread();
        }
    }
    

    inside the thread function:

    TCPSocket::TCPSocket()
    {
        socket = new QTcpSocket;
        connect(&server,SIGNAL(newConnection()),this,SLOT(newConnectionS()));
        connect(socket,SIGNAL(disconnected()),this,SLOT(Disconnected()));
        connect(&timer_,SIGNAL(timeout()),this,SLOT(Disconnected()));
        emit msg("Itializing server side...");
    }
    void TCPSocket::run(){
        if(server.isListening() ){
    
        }else{
            this->ListenS();
        }
    }
    


  • @mandruk1331 hi,
    first of, let me show you think link to the wiki page its quite useful for Qt and threading.

    to your problem,
    you create your socket object in the constructor of your class

    TCPSocket::TCPSocket()
    {
        socket = new QTcpSocket;
    

    that means the object is created here in the main thread:

    for(int i=0;i<4;i++){
            socketC = new TCPSocket;
    

    thats were your error msg is from.

    to fix that move the socket creation in your run function:

    void TCPSocket::run(){
        if(start){
            socket = new QTcpSocket;
            start = false;
        }
        if(server.isListening() ){
    
        }else{
            this->ListenS();
        }
    }
    

    but I would still suggest the worker abroach described in the wiki page. Than overwriting run of your Qthread class.

    edit: fixed format issue.



  • This post is deleted!

Log in to reply