QT development (seven) - timer events, system time, random numbers

Let's learn some small knowledge points, namely the timer time, system time, and random numbers. It should be explained here that events and signals are different. Don't confuse them. On the surface, they all seem to trigger a certain function. In fact, you can understand that time is more inclined to the bottom

1. Timer events

We actually learned about timers

In this small project, we use the timing trigger through the timeout signal. In fact, like the previous article, our QT also has corresponding events. Let's take a look:

  • void timerEvent(QTimerEvent * event);

Simple to use

this->id = startTimer(1000);

We directly call startTimer to specify the interval time, the unit is ms, and return an int, which is an id

void MainWindow::timerEvent(QTimerEvent *event)
{
    if(event->timerId() == this->id)
    {
        QDebug() << "触发";
    }
}

In this way, it will be triggered every 1s, if you want to stop the timer

killTimer(id);

Now discover the usefulness of this id!

2. System time

The acquisition of system time can be achieved in this way

QDateTime time = QDateTime::currentDateTime();
QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
this->ui->tv_time->setText(str);

We can get it through the static function currentDateTime of QDateTime and then convert the format, but here is a static value. If we want to implement a clock, we need to use the above timer, that is, our timer event should be like this to write:

void MainWindow::timerEvent(QTimerEvent *event)
{
    if(event->timerId() == this->id)
    {
        QDateTime time = QDateTime::currentDateTime();
        QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
        this->ui->tv_time->setText(str);
    }
}

In this way, the clock can be realized

write picture description here

3. Random numbers

The random number is a function qrand(), and his formula is

  • qrand() % N (N is followed by the interval 0 - N)

Let's implement a small case of moving, using the above example to handle, we randomly move the time control

void MainWindow::timerEvent(QTimerEvent *event)
{
    if(event->timerId() == this->id)
    {
        QDateTime time = QDateTime::currentDateTime();
        QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");
        this->ui->tv_time->setText(str);
        int a = qrand()%300;
        this->ui->tv_time->move(a,a);
    }
}

This will achieve the effect

write picture description here

Interested can join the group: 690351511

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325915809&siteId=291194637