使用QTimer創建定時器
QTimer主要使用兩個方法:QTimer timer;
timer.start(n ms);
開啓定時器,輸入參數爲每n 毫秒觸發一次timeout信號。
timer.stop();
停止定時器。
建立timeout信號與槽函數的連接:
connect(timer, SIGNAL(timeout()), this, SLOT(on_timeout()));
注意一定要先建立連接才能開始定時器。
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTimer>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private:
Ui::MainWindow *ui;
QTimer *timer;
private slots:
void on_timeout();
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <iostream>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
timer = new QTimer();
connect(timer, SIGNAL(timeout()), this, SLOT(on_timeout()));
timer->start(10);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_timeout()
{
std::cout << "do something" << std::endl;
timer->stop();
}