QThread and QObject



  • Hello

    I have a problem with Qthread. I would like to run a Functie of my Serial class in a thread. And start the thread in my mainwindow class.
    But when I run my application I get the following error:
    @Start Thread
    QThread: Destroyed while thread is still running
    The program has unexpectedly finished.
    Allflowlift.exe exited with code -1073741819@

    the Mainwindow
    @void MainWindow::Serial_Connect()
    {
    qDebug() << "Start Thread";
    QThread cThread;
    Serial sSerial;
    sSerial.Serial_Thread_Start(cThread);
    sSerial.moveToThread(&cThread);
    cThread.start();
    bSerialOn = true;
    }@

    The Serial.cpp:
    @Serial::Serial(QObject *parent)
    :QObject(parent)
    {
    }

    void Serial::Serial_Thread_Start(QThread &cThread)
    {
    connect(&cThread, SIGNAL(started()), this, SLOT(Test()));
    }

    void Serial::Test()
    {
    qDebug() << "Tread";
    }@

    The Serial.h

    @class Serial : public QObject
    {
    Q_OBJECT
    public:
    Serial(QObject *parent = 0);
    void Serial_Thread_Start(QThread &cThread);

    private slots:
    void Test();

    signals:

    };@

    Know someone maybe what I'm doing wrong?


  • Moderators

    You are declaring the thread on a stack. It goes out of scope on line 10. of the first snippet you've provided, and is destroyed. You should refactor that bit - either declare the thread in your MainWindow class, or use a pointer.



  • I have now set "QThread cThread;" in my mainwindow.h

    The applicatie run now but. The Thread run not the code of the Serial::Test() functie.

    The Serial.cpp
    @void Serial::Serial_Thread_Start(QThread &cThread)
    {
    connect(&cThread, SIGNAL(started()), this, SLOT(Test()));
    qDebug() << "Connect Thread";
    }

    void Serial::Test()
    {
    for(int i = 0; i < 100; i ++)
    {
    qDebug() << "Tread" << i;
    }
    }@



  • But you still did not follow sierdzio's advice to modify "Serial sSerial;", right?



  • I have declare the thread in my MainWindow.

    @namespace Ui {
    class MainWindow;
    }

    class MainWindow : public QMainWindow
    {
    Q_OBJECT

    public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

    private:
    QThread cThread;
    Ui::MainWindow *ui;
    };@



  • Yes, I see, but your

    @
    Serial sSerial;
    @

    still "goes out of scope on line 10. of the first snippet you’ve provided, and is destroyed. "



  • modify
    @Serial sSerial;
    sSerial.Serial_Thread_Start(cThread);
    sSerial.moveToThread(&cThread);@
    to:
    @Serial* sSerial=new Serial(this);
    sSerial->Serial_Thread_Start(cThread);
    sSerial->moveToThread(&cThread);@


Log in to reply
 

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