Qt 中QTimer在子线程中使用

如果想在程序中使用延时或者定时功能,一般使用sleep或者定时器QTimer。想要在子线程中使用QTimer改怎么使用呢?

第一次

线程类

#pragma once

#include <QThread>

class QTimer;

class QtMyThread : public QThread {
	Q_OBJECT

public:
	QtMyThread(QObject *parent);
	~QtMyThread();

private:
	void run()override;

private slots:
	void slotTimeOut();

signals:
	void sigFlag(int i);
private:
	QTimer* _timer = nullptr;

	int _i = 0;
};

#include "QtMyThread.h"
#include <QTimer>

QtMyThread::QtMyThread(QObject *parent)
	: QThread(parent) {
}

QtMyThread::~QtMyThread() {
}

void QtMyThread::run() {
	_timer = new QTimer();
	connect(_timer, SIGNAL(timeout()), this, SLOT(slotTimeOut()));
	_timer->start(1000);
}

void QtMyThread::slotTimeOut() {
	_i++;
	emit sigFlag(_i);
}

UI

#pragma once

#include <QtWidgets/QMainWindow>
#include "ui_Test.h"

class QtMyThread;

class Test : public QMainWindow {
	Q_OBJECT

public:
	Test(QWidget *parent = Q_NULLPTR);

private:
	void init();

private slots:
	void slotStartThread();
	void slotFlag(int i);
private:
	QtMyThread* _myThread = nullptr;
private:
	Ui::TestClass ui;
};

#include "Test.h"
#include "ThreadTimer/QtMyThread.h"

Test::Test(QWidget *parent)
	: QMainWindow(parent) {
	ui.setupUi(this);
	init();
}

void Test::init() {
	connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(slotStartThread()));

	_myThread = new QtMyThread(this);
	connect(_myThread, SIGNAL(sigFlag(int)), this, SLOT(slotFlag(int)));
}

void Test::slotStartThread() {
	_myThread->start();
}

void Test::slotFlag(int i) {
	ui.label->setText(QString::number(i));
}

在这里插入图片描述
当点击【开始】,发现定时器并没有运行
解决方案:需要在线程中添加时间循环处理函数 exec()

第二次

#include "QtMyThread.h"
#include <QTimer>

QtMyThread::QtMyThread(QObject *parent)
	: QThread(parent) {
}

QtMyThread::~QtMyThread() {
}

void QtMyThread::run() {
	_timer = new QTimer();
	connect(_timer, SIGNAL(timeout()), this, SLOT(slotTimeOut()));
	_timer->start(1000);
	exec();
}

void QtMyThread::slotTimeOut() {
	_i++;
	emit sigFlag(_i);
}

点击按钮【开始】定时器已经运行起来了,但是通过断点发现,定时器还是在主线程中运行的。
在这里插入图片描述
解决方案:connect默认的连接方式Qt::AutoConnection,需要改成Qt::DirectConnection

第三次

#include "QtMyThread.h"
#include <QTimer>

QtMyThread::QtMyThread(QObject *parent)
	: QThread(parent) {
}

QtMyThread::~QtMyThread() {
}

void QtMyThread::run() {
	_timer = new QTimer();
	connect(_timer, SIGNAL(timeout()), this, SLOT(slotTimeOut()), Qt::DirectConnection);
	_timer->start(1000);
	
	exec();
}

void QtMyThread::slotTimeOut() {
	_i++;
	emit sigFlag(_i);
}

这样就可以在子线程中运行定时器了
在这里插入图片描述
源码下载
aaa

  • 9
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wb175208

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值