QTimer类实现简单电子表与随机数

//widget.h
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
private slots:
    void timerUpdate();
private:
    Ui::Widget *ui;
};

#endif // WIDGET_H
//widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include<QTime>
#include<QTimer>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    QTimer *timer = new QTimer(this);
    timerUpdate();//使电子表一开始就显示时间而不是0
    connect(timer, &QTimer::timeout, this, &Widget::timerUpdate);//连接信号和槽
    timer->start(1000);//设置溢出时间为1s,并启动定时器
}

Widget::~Widget()
{
    delete ui;
}

void Widget::timerUpdate()
{
    QTime time = QTime::currentTime();//获取当前时间
    QString text = time.toString("hh:mm:ss");//时间格式
    if((time.second()%2) == 0)
    {
        text[2] = ' ';//隔一秒“:”闪一下
        text[5] = ' ';
    }
    ui->lcdNumber->display(text);//显示时间
}
//main.cpp
#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

效果如图:

在以上代码中添加代码:

//widget.cpp中的构造函数
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
//qsrand()设置不同初值,secsTo()表示两个时间点所包含的秒数(从零点到当前时间所经过的秒数)
//widget.cpp中的timerUpdate()
int rand = qrand() % 300;//生成0-299的随机数
ui->lcdNumber->move(rand, rand);//电子表移动

效果如图:

posted @ 2017-05-09 19:22  奇热行  阅读(250)  评论(0)    收藏  举报