Qt 多线程的简单应用

原文:https://blog.csdn.net/uyy203/article/details/52704059

MyThread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H
 
#include <QThread>
#include <QDebug>
 
class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = 0);
    ~MyThread();
 
 
protected:
        void run();
 
};
 
#endif // MYTHREAD_H

MyThread.cpp

#include "mythread.h"
 
MyThread::MyThread(QObject *parent) :
    QThread(parent)
{
}
 
MyThread::~MyThread()
{
 
}
 
void MyThread::run()//线程执行函数
{
 
        qDebug("MyThread!\n");
        QThread::msleep(1000);//线程休眠1000毫秒,相当于延时1s,实现每1秒从qDebug打印出"MyThread!"
 
}

MainWindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
 
#include <QMainWindow>
#include<mythread.h>
namespace Ui {
class MainWindow;
}
 
class MainWindow : public QMainWindow
{
    Q_OBJECT
 
public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
 
 
private slots:
    void on_pushButton_clicked();
 
 
    private:
    Ui::MainWindow *ui;
 
    MyThread *myThread;
};
 
#endif // MAINWINDOW_H

MainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    qDebug("mainwindow!\n");
 
    myThread=new MyThread;
 
}
 
MainWindow::~MainWindow()
{
    delete ui;
}
 
void MainWindow::on_pushButton_clicked()
{
        myThread->start();//启动线程
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容