Important: Please read the Qt Code of Conduct -

thread does not work

  • I do not know what the problem is?


    #ifndef MYTHREAD_H
    #define MYTHREAD_H
    #include <QThread>
    class MyThread : public QThread
        explicit MyThread(QObject *parent = 0);
        void run();
        bool Stop;
        void NumberChanged(int);
    public slots:
    #endif // MYTHREAD_H


    #include "mythread.h"
    #include <QtCore>
    MyThread::MyThread(QObject *parent) : QThread(parent)
    void MyThread::run()
        for(int i = 0; i < 10000; i++)
            QMutex mutex;
            if(this->Stop) break;
            emit NumberChanged(i);


    MainWindow::MainWindow(QWidget *parent) :
        ui(new Ui::MainWindow)
        setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::Window |  Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint);
        mThread = new MyThread(this);
    void MainWindow::onNumberChanged(int Number)
    void MainWindow::on_pushButton_clicked()

    output: QMutex: destroying locked mutex

  • Lifetime Qt Champion

    @MrErfan You're using a local mutex! Put it in your class as member variable and unlock it before break. All threads executing this code must use same mutex else there is no synchronisation! It is better to use QMutexLocker.
    Actually there is no need for this mutex at all in this case...

  • Re: thread does not work

    Thank you for your reply, but unfortunately Thread does not work.
    By clicking on the Start button, the program will hang ،
    If I use the QLabel, the program works properly, but I want to use QPlaintextedit

    void MainWindow::onNumberChanged(int Number)

  • Moderators

    @MrErfan try it with void QPlainTextEdit::appendPlainText(const QString &text) your TextEdit might not have a valid curse to use insert upon

  • @MrErfan
    This does not address your problem, but would your code be a lot nicer if you used QWaitCondition?

  • Moderators

    @JNBarchan For that what the code does, so far as shown to us, it would be more usefull to use QtConcurrent::run

  • @J.Hilk His run seems to be waiting for something to set this->Stop over a period of time, that seems to be just what QWaitCondition is for, but I am a beginner so bow to superior knowledge. I just discovered QWaitCondition an hour ago :)

Log in to reply