Qt 多线程的简单应用

来源:互联网 发布:88读书网软件 编辑:程序博客网 时间:2024/05/03 12:43

MyThread.h

#ifndef MYTHREAD_H#define MYTHREAD_H#include <QThread>#include <QDebug>class MyThread : public QThread{    Q_OBJECTpublic:    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_OBJECTpublic:    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();//启动线程}


0 0
原创粉丝点击