How to put a function to a new thread? (Display video with OpenCv) Multiple Errors :-(



  • Hello,

    I am a beginner with basic C++ knowledge.
    I really like Qt Creater and I want to learn the own Qt languge.
    Sadly for this time is missing a the moment :-(

    I would like to display a Webcam stream in a own thread.

    Because of using QtSerialPort I had to instantiate a QApplication and therefore I now have problems creating threads.

    Is there a possibility to create a QApplication just for the QtSerialPort functions that there is no special Qt stuff necessary in the rest of the program?

    I get multiple errors:
    QObject::moveToThread: Widgets cannot be moved to a new thread
    QObject: Cannot create children for a parent that is in a different thread.
    QSocketNotifier: Can only be used with threads started with QThread
    QObject::startTimer: Timers can only be used with threads started with QThread

    This is the minmal I used:
    @#include "opencv2/core/core.hpp"
    #include <opencv2/highgui/highgui.hpp>
    #include <opencv2/imgproc/imgproc.hpp>

    #include <iostream>
    #include <thread>

    #include <QCoreApplication>
    #include <QApplication>
    #include <QSerialPort>

    using namespace std;
    using namespace cv;

    QSerialPort serial;

    void InitialiseSerialPort()
    {

    serial.setPortName("/dev/ttyUSB0");
    serial.open(QIODevice::WriteOnly);
    serial.setBaudRate(QSerialPort::Baud19200);
    serial.setDataBits(QSerialPort::Data8);
    serial.setParity(QSerialPort::NoParity);
    serial.setStopBits(QSerialPort::OneStop);
    serial.setFlowControl(QSerialPort::NoFlowControl);
    }

    void DisplayWebCam ()
    {
    Mat frame;
    VideoCapture cap (0);
    namedWindow("Livebild");
    while(char(waitKey(10)) != 'q' && cap.isOpened())
    {
    cap >> frame;
    imshow("Livebild", frame);
    }
    }

    int main (int argc, char *argv[])
    {

    QApplication app(argc, argv);
    InitialiseSerialPort();
    
    serial.write("Test");
    serial.flush();
    //DisplayWebCam();  //Works!
    thread t1 (DisplayWebCam);  //Works not!
    
    t1.join();
    
    return 0;
    

    }@

    How can I solve my problem?

    Thank you very much :-)


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Short version: widget and GUI related stuff must be done in the GUI thread AKA main thread.

    OpenCV also has a Qt backend for its GUI, hence the errors you are seeing.

    Since your knowledge of C++ is currently limited, you should avoid starting directly with threads, it's one of the very complex part of programming.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.