相关资料:
https://blog.csdn.net/u014783974/article/details/81486491
main.cpp
1 #include "mainwindow.h" 2 3 #include <QApplication> 4 5 int main(int argc, char *argv[]) 6 { 7 QApplication a(argc, argv); 8 MainWindow w; 9 w.show(); 10 return a.exec(); 11 }
mainwindow.h
1 #ifndef MAINWINDOW_H 2 #define MAINWINDOW_H 3 4 #include <QMainWindow> 5 6 #include <QTimer> 7 8 QT_BEGIN_NAMESPACE 9 namespace Ui { class MainWindow; } 10 QT_END_NAMESPACE 11 12 class MainWindow : public QMainWindow 13 { 14 Q_OBJECT 15 16 public: 17 MainWindow(QWidget *parent = nullptr); 18 ~MainWindow(); 19 20 private slots: 21 void on_pushButton_clicked(); 22 void TimerTimeOut(); 23 void on_pushButton_2_clicked(); 24 void on_pushButton_3_clicked(); 25 26 private: 27 Ui::MainWindow *ui; 28 QTimer *m_timer; 29 void InitTimer(); 30 }; 31 #endif // MAINWINDOW_H
mainwindow.cpp
1 #include "mainwindow.h" 2 #include "ui_mainwindow.h" 3 4 MainWindow::MainWindow(QWidget *parent) 5 : QMainWindow(parent) 6 , ui(new Ui::MainWindow) 7 { 8 ui->setupUi(this); 9 setWindowTitle(QStringLiteral("Qt组件QTimer使用方法")); 10 InitTimer(); 11 } 12 13 MainWindow::~MainWindow() 14 { 15 delete ui; 16 } 17 18 19 void MainWindow::on_pushButton_clicked() 20 { 21 ui->textEdit->clear(); 22 } 23 24 void MainWindow::TimerTimeOut() 25 { 26 // //判断定时器是否运行 27 // if(m_timer->isActive()) 28 // m_timer->stop(); //停止定时器 29 ui->textEdit->append("------"); 30 31 } 32 33 void MainWindow::InitTimer() 34 { 35 if(NULL == m_timer) 36 m_timer = new QTimer; 37 //设置定时器是否为单次触发。默认为 false 多次触发 38 m_timer->setSingleShot(false); 39 //启动或重启定时器, 并设置定时器时间:毫秒 40 m_timer->start(1000); 41 //定时器触发信号槽 42 connect(m_timer, &QTimer::timeout, this, &MainWindow::TimerTimeOut); 43 44 } 45 46 void MainWindow::on_pushButton_2_clicked() 47 { 48 m_timer->start(); 49 } 50 51 void MainWindow::on_pushButton_3_clicked() 52 { 53 54 m_timer->stop(); 55 }