Unsolved QObject: cannot create children for a parent which is in a different thread
-
When I add to my code it causes the error: "QObject: cannot create children for a parent which is in a different thread"
socket->write("From server: hello world"); socket->flush(); socket->waitForBytesWritten();
#include "httpserver.h" HttpServer::HttpServer(QObject *parent) : QTcpServer(parent) { pool = new QThreadPool(this); } HttpServer::~HttpServer() { delete pool; } void HttpServer::setStorage(Storage *storage) { this->storage = storage; } void HttpServer::startServer() { if(listen(QHostAddress::Any, 1234)) { qDebug() << "Server started"; } else { qDebug() << "Server: not started"; } } void HttpServer::incomingConnection(qintptr socketDescriptor) { Runnable *task = new Runnable(); task->setAutoDelete(true); task->socketDescriptor = socketDescriptor; task->storage = storage; pool->start(task); }
//Runnable
#include "runnable.h" Runnable::Runnable(QObject *parent) : QObject(parent) { } void Runnable::run() { eventLoop = new QEventLoop(); socket = new QTcpSocket(); if(socket->setSocketDescriptor(socketDescriptor)) { connect(socket,SIGNAL(connected()),this,SLOT(onConnected()),Qt::QueuedConnection); connect(socket,SIGNAL(disconnected()),this,SLOT(onDisconnect()),Qt::QueuedConnection); connect(socket,SIGNAL(readyRead()),this,SLOT(onReadyRead()),Qt::QueuedConnection); } eventLoop->exec(); delete socket; delete eventLoop; } void Runnable::onConnected() { qDebug() << "Connected"; } void Runnable::onDisconnect() { qDebug() << "Disconnected"; eventLoop->exit(); } void Runnable::onReadyRead() { parse(socket->readAll()); } void Runnable::parse(QString httpRequest) { qDebug().noquote() << httpRequest; QRegularExpression methodRegExp("\\b(GET|POST)\\b"); QRegularExpressionMatch matchMethod = methodRegExp.match(httpRequest); if(matchMethod.hasMatch()) { QString method = matchMethod.captured(0); if(method == "GET") { } else if(method == "POST") { QRegularExpression uriRegExp("/(.*?)\\s"); QRegularExpressionMatch matchURI = uriRegExp.match(httpRequest); QString uri = matchURI.captured(0); uri.truncate(uri.lastIndexOf(QChar(' '))); qDebug() << uri; QRegularExpression bodyRegExp("(\[.*?\]|\\{.*?\\})"); QRegularExpressionMatch matchBody = bodyRegExp.match(httpRequest); qDebug() << matchBody; socket->write("From server: hello world"); socket->flush(); socket->waitForBytesWritten(); } } else { qDebug() << "No match"; } }
-
@Subuday said in QObject: cannot create children for a parent which is in a different thread:
When I add to my code
Add what?