Qt 中线程QThread的简单使用

实验说明: 将一个循环放到线程里运行,同时将信息显示在主界面上,使得主界面不卡。

1  main.cpp

#include <QtGui/QApplication>
#include "dialog.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog w;
    w.show();
    return a.exec();
}
2 dialog.h
#ifndef DIALOG_H
#define DIALOG_H

#include <QThread>
#include <QtCore>
#include <QtGui>
#include"mythread.h"

namespace Ui {
    class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();

private slots:
    void on_StartPthread_clicked();

    void on_StopPthread_clicked();

    void GetPthreadMessage(QString);

private:

    MyThread thread;

    Ui::Dialog *ui;
};

#endif // DIALOG_H
3 dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    connect(&thread,SIGNAL(sendMessage(QString)),this,SLOT(GetPthreadMessage(QString)));
    this->setFixedSize(300,100);
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::GetPthreadMessage(QString recv)
{
    ui->lineEdit->setText(recv);
    qDebug()<<recv;
}
void Dialog::on_StartPthread_clicked()
{
    thread.start(); //就会调用 MyThread里的run函数
    ui->StartPthread->setEnabled(false);
    ui->StopPthread->setEnabled(true);
}

void Dialog::on_StopPthread_clicked()
{
   if(thread.isRunning())
   {
       thread.stop(); //就会调用 MyThread里的stop函数
       ui->StartPthread->setEnabled(true);
       ui->StopPthread->setEnabled(false);
   }
}
4  mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>
#include <QtGui>
#include <QtCore>


class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = 0);

    void run();
    void stop();
    bool stopped;
    QString myString;
   

signals:

	 void sendMessage(QString);//sendMessage为自定义信号

public slots:

};

#endif // MYTHREAD_H
5 mythread.cpp

#include "mythread.h"

MyThread::MyThread(QObject *parent) :
    QThread(parent)
{
    stopped=false;
}

void MyThread::run()
{
    qreal i=0;
    while(!stopped)
    {
       qDebug()<<QString("in MyThread:%1").arg(i++);
       myString=QString("in MyThread:%1").arg(i++);
       emit sendMessage(myString);
       this->msleep(100); //如果不用msleep等函数延时,主界面会卡住.
    }
    stopped=!stopped;
}

void MyThread::stop()
{
    stopped=true;
}

6  效果图

线程开始

Qt 中线程QThread的简单使用_第1张图片

线程停止

Qt 中线程QThread的简单使用_第2张图片



你可能感兴趣的:(线程,qt,QHread)