qt线程相关知识

+++++++++++++++++++++++widght.h++++++++++++
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QDebug>
#include <QTimer>
#include <QThread>

#include "mythread.h"

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
public slots:
    void LCDstart();
    void dealDone();
    void stopThread();

private slots:
    void on_pushButton_clicked();

private:
    Ui::Widget *ui;
    QTimer *myTimer;
    myThread *thread;
};

#endif // WIDGET_H

+++++++++widget.cpp++++++++++++++  

#include "widget.h"
#include "ui_widget.h"

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

    myTimer = new QTimer;
    thread = new myThread;

    connect(myTimer,&QTimer::timeout,this,&Widget::LCDstart);
    connect(thread,&myThread::isDone,this,&Widget::dealDone);
    connect(this,&Widget::destroyed,this,&Widget::stopThread);
}

void Widget::stopThread()
{
    thread->quit();
    thread->wait();
    qDebug() << "thread is stop!";
}

void Widget::dealDone()
{
    qDebug()<< "is over!";
    myTimer->stop();
}

void Widget::LCDstart()
{
    static int i = 0;
    i++;
    ui->lcdNumber->display(i);
}

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

void Widget::on_pushButton_clicked()
{
    if(myTimer->isActive() == false)
    {
        myTimer->start(100);
    }

    thread->start();

//    QThread::sleep(5);
//    qDebug()<< "is over!";
//    myTimer->stop();
}

+++++++myThread.h+++++++++++++
#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>

class myThread : public QThread
{
    Q_OBJECT
public:
    explicit myThread(QObject *parent = nullptr);

protected:
    void run();

signals:
    void isDone();
public slots:
};

#endif // MYTHREAD_H

++++++myThread.cpp +++++++++++++++++

#include "mythread.h"

myThread::myThread(QObject *parent) : QThread(parent)
{

}

void myThread::run()
{
    sleep(5);
    emit isDone();
}

 

1、run函数是虚函数

 需要用start函数启动

 

定时器.isActive()是用来判断是否在使用中,这样保证是空闲时点击才生效,要是定时器开启了,再次点击将无效

sleep在线程中可以直接使用,在其余地方需要用QThread::sleep();

 

posted @ 2023-06-12 22:14  罗罗罗狗蛋  阅读(8)  评论(0编辑  收藏  举报