Solved error When use moveToThread
-
Hi, rencently I'm coding on a video processing program, and trying to move the time cost processing in to another thread, by subclassing QObject and move it to another thread by moveToThread.
class VideoEncoder : public QObject { VideoEncoder(); }
Here's an another class called VideoController, which manages VideoEncoder:
#include <QThread> #include "VideoEncoder.h" class VideoController : public QWidger { .... public: void init(); private: QThread *encoderThread_; VideoEncoder *videoEncoder_;
here's my moveToThread code.
void VideoController::init() { videoEncoder_ = new VideoEncoder; encoderThread_ = new QThread; videoEncoder_->moveToThread(encoderThread_); // Get Errors!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // cannot initialize object parameter of type 'QObject' with an expression of type 'VideoEncoder' }
If I move the line of
#include "VideoEncoder.h"
from header file to cpp file,
and add a forward declarationclass VideoEncoder
in header file
The error disappears.Could someone help me through it. It really confuses me.
-
Not directly related to your question, but your
VideoEncoder
is aQWidget
, and therefore must lie in the main thread. GUI objects must live in the main thread. -
@hikaris said in error When use moveToThread:
The error disappears.
Please show the full code. I would guess you create a circular include.
-
@JohanSolo nope, VideoEncoder is a QObject. VideoController is a QWidget, and it lives in main thread.
-
Did you forget to add
Q_OBJECT
forVideoEncoder
? -
@kshegunov no, I did add Q_OBJECT for VideoEncoder, and also VideoController
-
@hikaris After adding Q_OBJECT did you do a clean/run qmake/rebuild ?:
-
Again: please ost your both headers. I'm pretty sure there is a circular include which prevents the compiler from knowing that your class derives from QObject - that's exactly what the error message tells you, nothing else.
-
@Christian-Ehrlicher you are right, thank you.