引用
QTimer
The QTimer class provides repetitive and single-shot timers.
The QTimer class provides a high-level programming interface for timers. To use it, create a QTimer, connect its timeout() signal to the appropriate slots, and call start(). From then on, it will emit the timeout() signal at constant intervals.
使用QTimer类定义一个定时器,它可以不停重复,也可以只进行一次便停止
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(1000);
创建一个QTimer对象,将信号timeout()
与相应的槽函数相连,然后调用start()
函数。接下来,每隔一段时间,定时器便会发出一次timeout()信号
Qt多线程的实现
QThread::run()
QThread 是 Qt 中实现多线程的基础类,通过继承 QThread 类并重写其 run() 函数可以实现自定义线程逻辑
- 线程类
#ifndef WORKER_H
#define WORKER_H
#include <QThread>
class Worker : public QThread
{
public:
Worker();
void run();
void printFunc();
};
#endif // WORKER_H
#include "Worker.h"
#include <QDebug>
Worker::Worker()
{
}
void Worker::run()
{
qDebug()<<"子线程ThreadID: "<<QThread::currentThreadId();
}
void Worker::printFunc()
{
qDebug()<<"子线程成员函数ThreadID: "<<QThread::currentThreadId();
}
- main函数
#include <iostream>
#include <QDebug>
#include "Worker.h"
using namespace std;
int main()
{
Worker w;
w.start();
qDebug()<<"主线程ThreadID: "<<QThread::currentThreadId();
w.printFunc();
while (1)
{
}
return 0;
}
- 执行结果
子线程ThreadID: 0x4138
主线程ThreadID: 0x34b0
子线程成员函数ThreadID: 0x34b0
主线程和子线程执行的顺序不确定,偶尔主线程在前,偶尔子线程在前
子线程类的成员函数包括槽函数是运行在主线程当中的,只有run()函数运行在子线程中
如果在run()函数中调用子线程类成员函数,那么该成员函数运行在子线程中
- 在run()函数中调用子线程成员函数
#include "Worker.h"
#include <QDebug>
Worker::Worker()
{
}
void Worker::run()
{
qDebug()<<"子线程ThreadID: "<<QThread::currentThreadId();
printFunc();
}
void Worker::printFunc()
{
qDebug()<<"子线程成员函数ThreadID: "<<QThread::currentThreadId();
// emit doTask();
}
主线程ThreadID: 0x2140
子线程ThreadID: 0x2044
子线程成员函数ThreadID: 0x2044
QThread::moveToThread()
moveToThread() 是 Qt 中用于将对象移动到另一个线程的方法。通过调用 moveToThread() 函数,可以将一个 QObject 对象从当前线程移动到另一个线程中,从而实现对象在新线程中执行特定的任务
在多线程编程中,通常会使用 moveToThread() 方法来将耗时的任务或需要在单独线程中执行的逻辑移动到单独的线程中,以避免阻塞主线程(通常是 GUI 线程)的执行
- 线程类
#ifndef WORKER_H
#define WORKER_H
#include <QObject>
class Worker : public QObject
{
Q_OBJECT
public:
Worker();
void printFunc();
public slots:
void doWork();
void doWork2();
void doWork3();
signals:
void testdoWork3();
};
#endif // WORKER_H
#include "Worker.h"
#include <QDebug>
#include <QThread>
Worker::Worker()
{
}
void