QT程序新建一个线程

1、创建好一个QT应用程序

2、手动创建新线程类,继承QThread

  我这里新建的是下面 newthread.h 和 newthread.cpp 文件。

  newthread.h

#ifndef NEWTHREAD_H
#define NEWTHREAD_H

#include <QThread>

class NewThread : public QThread  //这里画底色部分要自己添加
{
public:
    NewThread();
    void run();  //重构QThread类的run函数
};

#endif // NEWTHREAD_H

  newthread.cpp

#include "newthread.h"
#include <QDebug>

NewThread::NewThread()  //新建文件时自己生成的函数
{
}

void NewThread::run() //这个函数运行你要执行的代码
{
    while(true)   
    {
        qDebug()<<"test thread";
        sleep(2);
    }
}

3、在你的QT应用主线程中启动新线程

  下面是我主线程的代码

#include "avs200_od_proction_test.h"
#include "ui_avs200_od_proction_test.h"
#include <string.h>
#include <QProcess>
#include <QDebug>
#include <QString>
#include "newthread.h"
avs200_od_proction_test::avs200_od_proction_test(QWidget
*parent) : QMainWindow(parent) , ui(new Ui::avs200_od_proction_test) { ui->setupUi(this); NewThread *myThread = new NewThread(); //创建新线程对象,执行该句时会执行 newthread.cpp 中的 NewThread::NewThread() 函数 myThread->start(); //启动线程, 停止线程是 myThread->stop() 在你需要停止的地方调用即可; } avs200_od_proction_test::~avs200_od_proction_test() { delete ui; }

 

posted @ 2022-11-29 18:20  白菜没我白  阅读(264)  评论(0编辑  收藏  举报