目录
1. 头文件
2. cpp文件
1. 头文件
声明一个QTimer *ptimer指针;
声明一个普通类函数 void func();
声明一个槽函数(与普通的函数一致,但可以与多个信号连接)void test();
#ifndef TIMER_H #define TIMER_H #include#include namespace Ui { class timer; } class timer : public QMainWindow { Q_OBJECT public: explicit timer(QWidget *parent = nullptr); QTimer *ptimer; void func(); ~timer(); public slots: void test(); private: Ui::timer *ui; }; #endif // TIMER_H
2. cpp文件
test()槽函数用于输出一个测试字符串
在func()中,首先初始化ptimer;
随后启动ptimer,start(10)表示10ms刷新一次定时器;
connect()表示将定时器连接test()函数,每次刷新定时器即刷新执行一次test()函数;
#include "timer.h" #include "ui_timer.h" #includetimer::timer(QWidget *parent) : QMainWindow(parent), ui(new Ui::timer) { ui->setupUi(this); func(); } void timer::test(){ qDebug() << "hello timer"; } void timer::func(){ ptimer = new QTimer(this); ptimer->start(10); connect(ptimer, SIGNAL(timeout()), this, SLOT(test())); } timer::~timer() { delete ui; }



