首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QDateTime::secsTo为不同QDateTime返回相同的值

QDateTime::secsTo为不同QDateTime返回相同的值
EN

Stack Overflow用户
提问于 2017-08-04 20:27:17
回答 2查看 1.5K关注 0票数 2

我最近写了一个秒表,注意到QDateTime::secsTo的一些奇怪的行为。我不确定这是一个bug还是一个特性(或者我只做了一个糟糕的实现;-)。

我的秒表代码可以简化为这个最小的示例,以产生有问题的结果(至少在Linux上使用QT5.7.1):

StopWatch.h

代码语言:javascript
复制
#ifndef STOPWATCH_H
#define STOPWATCH_H

#include <QDialog>
#include <QDateTime>

class QTimer;

class StopWatch : public QDialog
{
    Q_OBJECT

public:
    explicit StopWatch(QWidget *parent);

private slots:
    void update();

private:
    QTimer *m_timer;
    QDateTime m_targetTime;
};

#endif // STOPWATCH_H

StopWatch.cpp

代码语言:javascript
复制
#include "StopWatch.h"
#include <QDebug>
#include <QTimer>

StopWatch::StopWatch(QWidget *parent) : QDialog(parent)
{
    m_timer = new QTimer(this);
    m_timer->setTimerType(Qt::PreciseTimer);
    connect(m_timer, &QTimer::timeout, this, &StopWatch::update);
    m_targetTime = QDateTime::currentDateTime().addSecs(10);
    m_timer->start(1000);
}

void StopWatch::update()
{
    QDateTime currentDateTime = QDateTime::currentDateTime();
    qint64 secondsLeft = currentDateTime.secsTo(m_targetTime);
    qDebug() << secondsLeft;
}

这是输出的一部分:

代码语言:javascript
复制
4
3
2
1
0
0
-1
-2
-3
-4

所以我们来看看:QDateTime::secsTo为同一个QDateTime输出0,在前一秒输出一个QDateTime

我做了这件事

代码语言:javascript
复制
if (currentDateTime <= m_targetTime) {
    secondsLeft++;
}

但我不明白你的行为。为什么是这种情况?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-08-04 20:40:30

查看源代码http://code.qt.io/cgit/qt/qtbase.git/tree/src/corelib/tools/qdatetime.cpp

代码语言:javascript
复制
int QTime::secsTo(const QTime &t) const
{
    if (!isValid() || !t.isValid())
        return 0;

    // Truncate milliseconds as we do not want to consider them.
    int ourSeconds = ds() / 1000;
    int theirSeconds = t.ds() / 1000;
    return theirSeconds - ourSeconds;
}

看起来它需要两个小于1000的正整数,除以1000,然后互相相减。如果使用mSecsTo(),就不会出现这个问题。

票数 4
EN

Stack Overflow用户

发布于 2017-08-04 20:44:05

这是个四舍五入的问题。secsTo函数不会舍入最近的整数,而只是删除十进制部分(默认情况下,这是编译器所做的):

代码语言:javascript
复制
int QTime::secsTo(const QTime &t) const
{
    if (!isValid() || !t.isValid())
        return 0;

    // Truncate milliseconds as we do not want to consider them.
    int ourSeconds = ds() / 1000;
    int theirSeconds = t.ds() / 1000;
    return theirSeconds - ourSeconds;
}

或4.x版本:

代码语言:javascript
复制
int QTime::secsTo(const QTime &t) const
{
    return (t.ds() - ds()) / 1000;
}

所以你可能看到的是:

代码语言:javascript
复制
 4.8 -> 4
 3.8 -> 3
 2.8 -> 2
 1.8 -> 1
 0.8 -> 0
-0.2 -> 0
-1.2 -> -1
-2.2 -> -2
-3.2 -> -3
-4.2 -> -4

对于预期的结果,请使用如下所示:

代码语言:javascript
复制
qint64 secondsLeft = qRound64(currentDateTime.msecsTo(m_targetTime) / 1000.0);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45514993

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档