您的位置:首页 > 编程语言 > Qt开发

Qt5 定时器 QTimer 的测试

2015-10-16 13:21 495 查看
目录 Content
[hide]

代码实现

mainwindow.h

mainwindow.cpp

运行结果

源码下载

如果需要在程序中周期性的处理事件,比如每秒种触发一次事件,那么可以使用QTimer。注意 QTimer 和 QTime 是不同的。

本文参照《Qt
定时器Timer使用》的介绍,测试代码成功。新建一个 Widget 程序,一切保持默认,然后修改代码,在UI设计里添加一个Label控件。


代码实现


mainwindow.h

01
#ifndef
 MAINWINDOW_H
02
#define
 MAINWINDOW_H
03
04
#include
 <QMainWindow>
05
06
namespace
Ui
 {
07
class
MainWindow;
08
}
09
10
class
MainWindow
 :
public
QMainWindow
11
{
12
Q_OBJECT
13
14
public
:
15
explicit
MainWindow(QWidget
 *parent = 0);
16
~MainWindow();
17
18
private
:
19
Ui::MainWindow
 *ui;
20
21
private
slots:
22
void
timerUpDate();
23
};
24
25
#endif
 // MAINWINDOW_H


mainwindow.cpp

01
#include
 "mainwindow.h"
02
#include
 "ui_mainwindow.h"
03
#include
 <QtCore>
04
05
MainWindow::MainWindow(QWidget
 *parent) :
06
QMainWindow(parent),
07
ui(
new
Ui::MainWindow)
08
{
09
ui->setupUi(
this
);
10
QTimer
 *timer =
new
QTimer(
this
);
11
connect(timer,SIGNAL(timeout()),
this
,SLOT(timerUpDate()));
12
timer->start(1000);
13
}
14
15
MainWindow::~MainWindow()
16
{
17
delete
ui;
18
}
19
20
void
MainWindow::timerUpDate()
21
{
22
QDateTime
time
=
 QDateTime::currentDateTime();
23
QString
 str =
time
.toString(
"yyyy-MM-dd
 hh:mm:ss dddd"
);
24
ui->label->setText(str);
25
26
}


运行结果

运行结果,程序每秒更新窗口label文本。




源码下载

qtimer_test

扩展阅读

QT 定时器QTimer

http://inching.org/2014/05/09/qt-timer/

from: http://davidrobot.com/2014/12/qt5-qtimer.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: