Error: working with QThreads
-
I'm getting this error while ussing QThreads:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QNetworkAccessManager(0x15694420), parent's thread is QThread(0x15670d00), current thread is CaptureThread(0x156f0ea8)I'm using an Api to save and get data from the Data Base, but when I try to save some information in the Thread I got that Error.
Can some help me out wiht this problem.
-
Ok, this it's the header of the QThread.
#ifndef CAPTURETHREAD_H #define CAPTURETHREAD_H #include <QThread> #include <QMutex> #include <QWaitCondition> #include <QJsonObject> #include "api.h" class CaptureThread : public QThread { Q_OBJECT public: explicit CaptureThread(Api *capi, QObject *parent = 0); void run(); void pause(); void resume(); bool flagpause; bool Stop; int countTime; QMutex sync; QWaitCondition pauseCond; QString url; Api* api; QJsonObject jsonUser; QJsonObject jsonSession; int idTask; signals: void counTimeChange(int countTime); }; #endif // CAPTURETHREAD_H
Api it's the class with the methods to access the database through an api.
The implementation
#include "capturethread.h" #include <QDesktopWidget> #include <QApplication> #include <QDir> #include <QDate> CaptureThread::CaptureThread(Api *capi, QObject *parent): QThread(parent) { this->countTime = 0; this->api = capi; } void CaptureThread::run(){ while (true) { api->createLog(api->jsonUser["id"].toInt(),api->jsonSession["id"].toInt()); this->msleep(60000); QDesktopWidget* dw = QApplication::desktop(); QPixmap pixmap = QPixmap::grabWindow( dw->winId(), 0, 0, dw->width(), dw->height() ); QDir mDir(QDir::homePath()); QString format = "jpg"; QString filename = "/screenshot_" + QString::number(QDate::currentDate().year())+ "_" +QString::number(QDate::currentDate().month())+ "_" +QString::number(QDate::currentDate().day())+ "_" +QString::number(QTime::currentTime().hour())+ "_" +QString::number(QTime::currentTime().minute())+ "_" +QString::number(QTime::currentTime().second()); QString mPath = QDir::homePath() + "/user"; if (!mDir.exists(mPath)) mDir.mkpath(mPath); pixmap.save(mPath+filename+".jpg", format.toLatin1().constData()); this->url = mPath+filename+".jpg"; api->closeLog(api->jsonUser["id"].toInt(),api->jsonLog["id"].toInt(), url); this->countTime ++; emit counTimeChange(this->countTime); sync.lock(); if(flagpause) pauseCond.wait(&sync); sync.unlock(); } } void CaptureThread::pause() { sync.lock(); flagpause = true; sync.unlock(); } void CaptureThread::resume() { sync.lock(); flagpause = false; sync.unlock(); pauseCond.wakeAll(); }
The main thread, the class task
capThread = new CaptureThread(currentapi,this); . . . . void Task::on_btnStart_clicked() { capThread->flagpause = false; capThread->resume(); capThread->start(); }