QThread QT线程使用案例

来源:互联网 发布:办公室网络维护 编辑:程序博客网 时间:2024/05/16 17:34

1.工程文件一共5个,创建2个线程,同时主界面一个按钮可以点击。

   分别是 main.cpp, mainwindow.cpp,  mainwindow.h,   mythread.cpp,   mythread.h .

2.

1).main.cpp代码如下:

#include "mainwindow.h"#include <QApplication>#include "mythread.h"int main(int argc, char *argv[]){    QApplication a(argc, argv);    MainWindow w;    w.show();        Mythread tha;    Mythread thb;    tha.start();    thb.start();    return a.exec();}

2).mianwindow.cpp代码如下:

#include "mainwindow.h"#include "ui_mainwindow.h"#include "mythread.h"#include <QDebug>MainWindow::MainWindow(QWidget *parent) :    QMainWindow(parent),    ui(new Ui::MainWindow){    ui->setupUi(this);}MainWindow::~MainWindow(){    delete ui;}void MainWindow::on_pushButton_clicked(){    qDebug()<<"on_pushButton_clicked";}


3).mainwindow.h代码如下:

#ifndef MAINWINDOW_H#define MAINWINDOW_H#include <QMainWindow>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;};#endif // MAINWINDOW_H

4).mythread.cpp代码如下:

#include "mythread.h"#include <QDebug>#include <QString>Mythread::Mythread(QObject *parent) :    QThread(parent){}void Mythread::run(){     for(int count=0; count<20; count++)    {        sleep(1);        qDebug()<<"Ping+"<<this->currentThreadId()<<count+1;     }}

5).mythead.h 代码如下:

#ifndef MYTHREAD_H#define MYTHREAD_H#include <QThread>class Mythread : public QThread{    Q_OBJECTpublic:    explicit Mythread(QObject *parent = 0);    signals:    public slots:public :    virtual void run();};#endif // MYTHREAD_H

3.运行结果:


1 0
原创粉丝点击