QTimer
2016-04-07 11:18
716 查看
Qt基础:定时器
通常情况下,可以通过两种方式使用定时器:1
使用QTimerEvent的timerId()函数来获取定时器的编号,然后根据不同编号处理不同操作. 2通过信号和槽实现定时器,即关联定时器溢出信号到溢出处理槽函数.
Demo
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> namespace Ui { class widget; } class QLCDNumber; class QDateTimeEdit; class widget : public QWidget { Q_OBJECT public: widget(QWidget *parent = 0); ~widget(); protected: void timerEvent(QTimerEvent *event); private slots: //定时器溢出处理 void timerUpdate(); private: Ui::widget *ui; //获取定时器编号 int id1; int id2; int id3; QLCDNumber *lcdNumber; QDateTimeEdit *dtEdit; }; //////////////////////////////////////////////////// #include <QtGui> #include "widget.h" #include "ui_widget.h" widget::widget(QWidget *parent) : QWidget(parent), ui(new Ui::widget) { ui->setupUi(this); //1` 开启三个定时器,返回其ID id1 = startTimer(1000); id2 = startTimer(2000); id3 = startTimer(3000); //2` 创建新的定时器 QTimer *timer = new QTimer(this); //关联 connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate())); timer->start(1000); lcdNumber = new QLCDNumber(this); //设置样式 lcdNumber->resize(100,22); //显示8个字符 lcdNumber->setDigitCount(8); //Outline,轮廓突出,颜色为背景色;Filled,内部填充型,颜色为黑色;Flat,平面型 lcdNumber->setSegmentStyle(QLCDNumber::Flat); //设置背景色 lcdNumber->setStyleSheet("background-color:yellow"); dtEdit = new QDateTimeEdit(this); dtEdit->setReadOnly(true); dtEdit->move(200,0); //随机数种子:两个时间点之间所有秒数 qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); } widget::~widget() { delete ui; } void widget::timerEvent(QTimerEvent *event) { if(event->timerId() == id1){ qDebug() << "timer1"; } else if(event->timerId() == id2){ qDebug() << "timer2"; } else { qDebug() << "timer3"; } } void widget::timerUpdate() { // QTime time = QTime::currentTime(); //获取当前时间 // QString text = time.toString("hh:mm"); //转换为字符串 // if((time.second() % 2) == 0) { // text[2] = ' '; //每隔1s ':' 换成空格 // } // lcdNumber->setText(text); lcdNumber->display(QTime::currentTime().toString("hh:mm:ss")); dtEdit->setDateTime(QDateTime::currentDateTime()); int rand = qrand() % 300; //动画效果 lcdNumber->move(rand,rand); }
字体设置 : http://qtcn.org/bbs/simple/?t55176.html
相关文章推荐
- QT学习 第一章:基本对话框
- 使用Shiboken为C++和Qt库创建Python绑定
- Qt 5.6更新至RC版,最终版本近在咫尺
- Qt定时器和随机数详解
- Qt实现图片移动实例(图文教程)
- Qt for Android开发实例教程
- QModelIndex/Role/Model介紹<二>
- 基于PyQt5的快速开发框架QFramer
- OSX下安装PyQt
- ok6410开发板移植DirectFB手记
- 【笔记】给Qt内嵌一个Chrome吧
- 【算法】最短路径之A*搜索
- qt入门必备
- 在 Qt4 中使用 C++11
- Hello Word ~ v0.2.2 背单词软件发布 -- By WHYPRO
- ubuntu下opencv和qt的安装配置
- linux下opengl的安装(with qt)
- qt 学习小节
- QT编译时Cannot find -lGL
- QT的命名风格