close

A good example for writing QThread with a GUI.



Here is another similar example:

QT5 TUTORIAL QTHREADS - GUI THREAD - 2020


image


image


image

Create a new class named MyThread, which inherits from QObject



image

This is what it looks like in the beginning in mythread.h

You can see that MyThread class, which inherits from QThread, is going to be added with some functions.

image

mythread.cpp

image


Once you key in the keyword “run”, a sequence of words automatically pops up. Press ENTER button

to add an override function easily.

image

Secondly, click right mouse button and a pop-up menu is shown. Choose “Refactor” and it will help you add its implenmentation of new function in mythread.cpp


image


Then add something in the run function.

image

And add a  mechanics of stopping while-loop, like this

#ifndef MYTHREAD_H
#define MYTHREAD_H
 
#include <QThread>
#include <QDebug>
 
class MyThread : public QThread
{
    Q_OBJECT
public:
    MyThread();
    void run() override;
    bool Stop = false;
};
 
#endif // MYTHREAD_H



image


image


image


mythread.cpp

#include "mythread.h"
 
MyThread::MyThread()
{
 
}
 
void MyThread::run()
{
    for(int i=0; i<10000; i++)
    {
        if(this->Stop)
        {
            break;
        }
        qDebug() << QString::number(i);
        this->msleep(10);
    }
}

In case of dead-lock, a mutex lock and unlock should be added. So here it goes

image

void MyThread::run()
{
    this->Stop = false;
    for(int i=0; i<10000; i++)
    {
        QMutex mutex;
        mutex.lock();
        if(this->Stop)
        {
            break;
        }
        mutex.unlock();
 
        qDebug() << QString::number(i);
        this->msleep(10);
    }
}

And now in order to display the number on the GUI instead of using qDebug. we are going to do two steps to complete it.

1. add a sender or say a signal named signalNumberChanged in mythread.h

2. add a receiver or say slot called slotNumberChanged in dialog.h.

mythread.h

image

mythread.cpp


image

dialog.h

image


image

#include "dialog.h"
#include "ui_dialog.h"
 
Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Dialog)
{
    ui->setupUi(this);
    th = new MyThread();
    connect(th, SIGNAL(signalNumberChanged(int) ),
            this, SLOT(slotNumberChanged(int)));
}
 
Dialog::~Dialog()
{
    delete ui;
}
 
 
void Dialog::on_pushButton_start_clicked()
{
    th->start();
}
 
void Dialog::on_pushButton_stop_clicked()
{
    th->Stop =true;
}
 
void Dialog::slotNumberChanged(int counter)
{
   //qDebug() << "slotNumberChanged:: " << QString::number(counter);
   ui->label->setText(QString::number(counter));
}


image

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 me1237guy 的頭像
    me1237guy

    天天向上

    me1237guy 發表在 痞客邦 留言(0) 人氣()