I have a QProcess
handler class (processHandler
) that is called inside my GUI
class as follows:
this->thread = std::make_shared<QThread>();
this->proc = std::make_shared<processHandler>();
this->proc->moveToThread(thread.get());
connect(this->thread.get(), SIGNAL(started()), this->proc.get(), SLOT(runProcess()));
The runProcess
SLOT is defined as follows in the processhandler.cpp
:
#include "processhandler.h"
processHandler::processHandler(QObject *parent) : QObject(parent)
{
this->proc = std::make_shared<QProcess>();
connect(this->proc.get(), SIGNAL(readyReadStandardError()), this, SLOT(printError()));
connect(this->proc.get(), SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(onProcessFinished(int, QProcess::ExitStatus)));
}
processHandler::~processHandler(){}
void processHandler::runProcess()
{
this->proc->setWorkingDirectory("path/to/application/dir");
this->proc->start("command");
}
void processHandler::printError()
{
QFile file("sys.log");
if (file.open(QIODevice::WriteOnly | QIODevice::Append))
{
QTextStream stream(&file);
QByteArray byteArray = this->proc->readAllStandardError();
QStringList strLines = QString(byteArray).split("\n");
QString now = QTime::currentTime().toString();
stream << "\n" << "Error Occurerd [" + now + "]: ";
foreach (QString line, strLines)
{
stream << line << endl;
}
}
file.flush();
file.close();
}
void processHandler::onProcessFinished(int exitCode, QProcess::ExitStatus status)
{
QFile file("sys.log");
if (file.open(QIODevice::WriteOnly | QIODevice::Append))
{
QTextStream stream(&file);
QString now = QTime::currentTime().toString();
stream << "\n" << "Process Exit [" + now + "]: " << QString::number(exitCode) << " with status " << QString::number(status);
}
file.flush();
file.close();
emit processFinished();
}
Once my thread
starts inside the GUI
class (this->thread->start();
), I recieve the following message:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QProcess(0x15c50cc), parent's thread is QThread(0x15526f0), current thread is QThread(0x15bb654)
I understand from the message, that the children of processHandler
live in another (main
?) thread. But I have not find any step-by-step explanation on stack overflow, how to creat those children before moving to the thread
. All hints or links that I missed are really appreciated.