我有一个QProcess
处理程序类(processHandler
)在我的GUI
类中调用,如下所示:
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()));
runProcess
中的processhandler.cpp
SLOT定义如下:
#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();
}
我的thread
课程(GUI
)内部this->thread->start();
开始后,我收到以下消息:
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)
我从消息中了解到,processHandler
的孩子生活在另一个(main
?)主题中。但我没有找到任何关于堆栈溢出的逐步解释,如何在转移到thread
之前创建这些孩子。我错过的所有提示或链接都非常感激。