当前位置: 首页 > article >正文

写了一个QT的定时器

主程序

#include <QCoreApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    MainWindow w;
    return a.exec();
}

mainwindow.cpp程序

#include "mainwindow.h"

#include <QDateTime>

MainWindow::MainWindow(QObject *parent)
    :QObject(parent)
{
    pTimer = new QTimer(this);
    pTimer->setInterval(10000);
    connect(pTimer, &QTimer::timeout, this, &MainWindow::slot10000msTimeOut);
    pTimer->start();
    qDebug() << "Start constructing MainWindow at:" << QDateTime::currentDateTime();

    if (pTimer->isActive()) {
        qDebug() << "Timer started successfully.";
    } else {
        qDebug() << "Timer failed to start.";
    }
}
MainWindow::~MainWindow()
{
    if(pTimer->isActive()){
        pTimer->stop();
    }
}

void MainWindow::slot10000msTimeOut()
{
    qDebug() << "End constructing MainWindow at:" << QDateTime::currentDateTime();
}

mainwindow.h头文件

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTimer>
#include <QDebug>
class MainWindow : public QObject
{
    Q_OBJECT

public:
    MainWindow(QObject *parent = nullptr);
    ~MainWindow();

private:
    QTimer *pTimer;



private slots:
    void slot10000msTimeOut();
};
#endif // MAINWINDOW_H

总结了注意点:

关闭定时器,在程序结束的时候,再stop

声明了槽函数,是必须要去定义的。否则报错

QCoreApplication不依赖于任何 GUI 相关的库和功能

 


http://www.kler.cn/a/585585.html

相关文章:

  • Deny by project hooks setting ‘default‘: size of the file
  • 深度学习和机器学习的差异
  • linux 命令 tail
  • 前端npm包- CropperJS
  • nginx: [error] invalid PID number ““ in “/usr/local/nginx/logs/nginx.pid“
  • 触控板 vs 数位板:远程设计作业外设适配报告
  • 编程自学指南:java程序设计开发,多线程编程,为什么需要多线程?线程的创建与启动,线程同步与锁机制,线程池
  • 多线程程序的测试和调试_第11章_《C++并发编程实战》笔记
  • 吴恩达机器学习笔记复盘(四)线性回归模型概述
  • 【Java】——运算符详解
  • PGSQL基本使用
  • SQLite?低调不是小众...
  • 红色警戒2:共和国之辉红警语音台词是什么?
  • 自适应二值化及伪影
  • RabbitMQ消息持久化与Lazy模式对比分析
  • 每日一题——逆波兰表达式
  • DeepSeek API 客户端使用文档
  • Spring Boot对接twilio发送邮件信息
  • Docker 部署Spring boot + Vue(若依为例)
  • Linux系统下安装Gedit文本编辑器的完整指南