Reputation: 479
I am using QT5.51. Why is t1 invalid?:
QTime t1 = QTime().addSecs(122);
qDebug() << t1.isValid() << t1.toString("hh:mm:ss");
I expected to get "00:02:02" , but I get false "".
Upvotes: 1
Views: 3445
Reputation: 126777
A newly default-constructed QTime
object starts in an invalid state.
QTime::QTime()
Constructs a null time object. A null time can be a
QTime(0, 0, 0, 0)
(i.e., midnight) object, except thatisNull()
returnstrue
andisValid()
returnsfalse
.
Adding seconds to an invalid time leaves it as invalid - after all, it's an invalid time point, not midnight as you seem to expect. It's pretty much a NaN-type behavior.
QTime QTime::addSecs(int s) const
...
Returns a null time if this time is invalid.
To create a QTime
in a valid state you can either use the other constructor
QTime::QTime(int h, int m, int s = 0, int ms = 0)
Constructs a time with hour h, minute m, seconds s and milliseconds ms.
so a midnight-initialized QTime
would be QTime(0, 0)
; OP code should thus be adjusted like this:
QTime t1 = QTime(0, 0).addSecs(122);
qDebug() << t1.isValid() << t1.toString("hh:mm:ss");
You can also use several other helper static methods, depending on how you need to initialize it.
Upvotes: 2
Reputation: 479
I think I got it:
QTime t1(0,0,0,0);
t1 = t1.addSecs(122);
qDebug() << t1.isValid() << t1.toString("hh:mm:ss");
= true "00:02:02"
Upvotes: 3