Qt 多线程的简单应用

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

MyThread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H
 
#include 
#include 
 
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 
#include
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();//启动线程
}

你可能感兴趣的:(Qt 多线程的简单应用)