qt开一个线程,在固定时间比如每500毫秒,调用一次打印helloword的函数
时间: 2024-02-06 14:08:51 浏览: 33
可以使用QTimer类来实现定时器功能,创建一个新线程并在其中启动QTimer即可。
以下是示例代码:
```cpp
#include <QCoreApplication>
#include <QThread>
#include <QTimer>
#include <QDebug>
class MyWorker : public QObject
{
Q_OBJECT
public slots:
void printHelloWorld()
{
qDebug() << "Hello World!";
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 创建新线程
QThread* thread = new QThread;
// 创建定时器,并设置定时时间为500毫秒
QTimer* timer = new QTimer;
timer->setInterval(500);
// 创建MyWorker对象,并将它移到新线程中
MyWorker* worker = new MyWorker;
worker->moveToThread(thread);
// 在定时器的timeout信号触发时,调用MyWorker的printHelloWorld槽函数
QObject::connect(timer, &QTimer::timeout, worker, &MyWorker::printHelloWorld);
// 在新线程启动前,启动定时器
QObject::connect(thread, &QThread::started, timer, static_cast<void (QTimer::*)()>(&QTimer::start));
// 在新线程退出后,停止定时器
QObject::connect(thread, &QThread::finished, timer, &QTimer::stop);
// 开始新线程
thread->start();
return a.exec();
}
```
运行该程序后,每500毫秒就会在控制台输出一次“Hello World!”。注意,程序需要等待QCoreApplication的事件循环结束才能退出,因此需要调用a.exec()。