c++qt5.5qtime

QTime add seconds to new object


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


Solution

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