1

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 "".

Paul G.
  • 461
  • 6
  • 21
  • I have to mention that I recently changed from qt4 to qt5. I looked at the "C++ API changes" and found "Adding days to a null QDate or seconds to a null QTime will no longer return a valid QDate/QTime." Maybe thats the reason. http://doc.qt.io/qt-5/sourcebreaks.html – Paul G. Jun 13 '16 at 06:25

2 Answers2

3

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"
Paul G.
  • 461
  • 6
  • 21
2

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 that isNull() returns true and isValid() returns false.

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.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
  • So I changed to QTime t1(0, 0, 0, 0); t1.addSecs(122)... It gets "true" but it doesnt add anything, why? If I assign t1.addSecs(122) to a new invalid QTime object "t2" it works. – Paul G. Jun 13 '16 at 06:37
  • 1
    because `addSeconds` doesn't add to the current object, but returns a new one with the added seconds – Karsten Koop Jun 13 '16 at 06:45
  • This answer should include information on how to create a valid QTime object. – Philipp Ludwig Mar 04 '21 at 10:24
  • @PhilippLudwig IDK there are various ways, and all seem obvious once you read the linked documentation; there's a constructor taking hours minutes, seconds and milliseconds, there are static methods to parse strings, taking the current time and many others... it's all in the doc. – Matteo Italia Mar 04 '21 at 10:43