我最近写了一个秒表,注意到QDateTime::secsTo的一些奇怪的行为。我不确定这是一个bug还是一个特性(或者我只做了一个糟糕的实现;-)。
我的秒表代码可以简化为这个最小的示例,以产生有问题的结果(至少在Linux上使用QT5.7.1):
StopWatch.h
#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_HStopWatch.cpp
#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;
}这是输出的一部分:
4
3
2
1
0
0
-1
-2
-3
-4所以我们来看看:QDateTime::secsTo为同一个QDateTime输出0,在前一秒输出一个QDateTime。
我做了这件事
if (currentDateTime <= m_targetTime) {
secondsLeft++;
}但我不明白你的行为。为什么是这种情况?
发布于 2017-08-04 20:40:30
查看源代码http://code.qt.io/cgit/qt/qtbase.git/tree/src/corelib/tools/qdatetime.cpp
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(),就不会出现这个问题。
发布于 2017-08-04 20:44:05
这是个四舍五入的问题。secsTo函数不会舍入最近的整数,而只是删除十进制部分(默认情况下,这是编译器所做的):
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版本:
int QTime::secsTo(const QTime &t) const
{
return (t.ds() - ds()) / 1000;
}所以你可能看到的是:
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对于预期的结果,请使用如下所示:
qint64 secondsLeft = qRound64(currentDateTime.msecsTo(m_targetTime) / 1000.0);https://stackoverflow.com/questions/45514993
复制相似问题