简体   繁体   中英

I'm trying to figure out how to use threads in a simple Qt gui application

In the simple example code I have, there is a start and stop button and a counter. When you press start, a thread is created and it increments the counter until you press stop. The click events are all working, but the thread itself does not start when it is called from dialog.cpp and the counter never increments. Any ideas why??

The code is from this guy's tutorial exactly as he did it here, and his worked: http://www.voidrealms.com/viewtutorial.aspx?id=79

dialog.h

#ifndef DIALOG_H
#define DIALOG_H

#include "mythread.h"
#include <QDialog>

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();
    MyThread *mThread;

private:
    Ui::Dialog *ui;

public slots:
    void onNumberChanged(int);

private slots:
    void on_pushButton_clicked();
    void on_pushButton_2_clicked();
};

#endif // DIALOG_H

dialog.cpp

#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    mThread = new MyThread(this);
    connect(mThread,SIGNAL(NumberChanged(int)), this, SLOT(onNumberChanged(int)));
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::onNumberChanged(int Number){
    ui->label->setText(QString::number(Number));
}

void Dialog::on_pushButton_clicked()
{
    mThread->start();
}

void Dialog::on_pushButton_2_clicked()
{
    mThread->Stop = true;
}

mythread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>

class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = 0);
    void run();
    bool Stop;

signals:
    void NumberChanged(int);

public slots:

};

#endif // MYTHREAD_H

mythread.cpp

#include "mythread.h"
#include <QtCore>

MyThread::MyThread(QObject *parent) :
    QThread(parent)
{
}


void MyThread::run() {

    for (int i = 0; i < 100000; i++) {
        QMutex mutex;
        mutex.lock();
        if (this->Stop) break;
        mutex.unlock();

        emit NumberChanged(i);
    }
}

Thank you!

After looking at the example code from the website you linked, I found at least two issues:

1) The Stop member variable is being used uninitialized, changing the constructor to look like this should fix your main issue:

MyThread::MyThread(QObject *parent) :
    QThread(parent),
    Stop(false)
{
}

2) The Stop variable never gets reset, so pushing the start/stop buttons only works once. It will work better if the break statement also resets the flag:

if (this->Stop)
{
    Stop = false;
    break;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM