Qt 简单线程测试

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();

signals:
    void dataChange();

private slots:
    void onTimeOut();
    void onPushButtonClicked();
private:
    Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H

worker.h****************************

#ifndef WORKER_H
#define WORKER_H

#include <QObject>

class Worker : public QObject
{
    Q_OBJECT
public:
    //explicit Worker(QObject *parent = nullptr);
    explicit Worker(QObject *parent = NULL);

signals:

public slots:
    void onStarted();
    void onDataChange();
};
#endif // WORKER_H

mainwindow.cpp***************************************

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "worker.h"
#include <QDebug>
#include <QThread>
#include <QTimer>

// QMutex      QMutexLocker
// QSemaphore
// QWaitCondition

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect( ui->pushButton, SIGNAL(clicked(bool)),
             this, SLOT(onPushButtonClicked()) );

    QTimer *tm = new QTimer;
    connect( tm, SIGNAL(timeout()),
             this, SLOT(onTimeOut()));
    tm->start(1000);

    Worker *w = new Worker;

    connect( this, SIGNAL(dataChange()),
             w, SLOT(onDataChange()), Qt::QueuedConnection);

    QThread *th = new QThread;
    connect( th, SIGNAL(started()),
             w, SLOT(onStarted()));
    w->moveToThread(th);
    th->start(QThread::HighestPriority);
}

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

void MainWindow::onTimeOut()
{
    static int i = 0;
    ui->lineEdit->setText(QString::number(i++));
}

void MainWindow::onPushButtonClicked()
{
    qDebug() << "pushbutton";
    emit dataChange();
}

worker.cpp****************************

#include "worker.h"
#include <QThread>
#include <QDebug>
#include <QTimer>

Worker::Worker(QObject *parent) : QObject(parent)
{
    QTimer *tm = new QTimer;
    connect( tm, SIGNAL(timeout()), this, SLOT(onStarted()));
    tm->start(1000);
}

void Worker::onStarted()
{
    static int i = 0;
        qDebug() << "worker started:"<< i++;
        QThread::sleep(1);
}

void Worker::onDataChange()
{
    qDebug() << "onDataChange()";
    QThread::sleep(5);
}
发布了12 篇原创文章 · 获赞 3 · 访问量 1463
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览