Why does the QMultiMap function not work as I expected?

I have QMultiMap<QDateTime, SomeOwnDataType>

one from which I would like to get all values ​​with a specific timestamp. This is what I am doing:

QMap<QDateTime, Appointment>::iterator it = _reminders.find(now);


where now

is di 6.mrt 12:07:00 2012. This is my loop condition:

while (it != _reminders.end() && it.key() == now) {


This was the state of the object _reminders



Contrary to my expectations, the cycle was skipped entirely. Why?


source to share

2 answers

I believe the problem is that the two timestamps are not equal. If you check the operator code ==


, you can see that equality is satisfied if both time and date values ​​are equal.

bool QDateTime::operator==(const QDateTime &other) const
    if (d->spec == other.d->spec && d->utcOffset == other.d->utcOffset)
        return d->time == other.d->time && d->date == other.d->date;
    else {
        QDate date1, date2;
        QTime time1, time2;

        d->getUTC(date1, time1);
        other.d->getUTC(date2, time2);
        return time1 == time2 && date1 == date2;


But the equal time operator compares milliseconds:

bool operator==(const QTime &other) const { return mds == other.mds; }


where mds

is the time in milliseconds. QTime


Calculated in the constructor as follows:

 mds = (h*SECS_PER_HOUR + m*SECS_PER_MIN + s)*1000 + ms;


It would be safer if you only check if the difference between the two timestamps is within the limit. For example:

while (it != _reminders.end() && abs(now.msecsTo(it.key())) < aLimitInMsecs) {




How do you initialize now



increases to a millisecond, so it toString()

can display the same value, while in fact the values ​​are different ... If at some point the key _reminders [0] is not set to a value now

, they will be different.

If you are creating a calendar application, you can use it QString

as a key to yours QMultiMap

, and the values ​​will be displayed QDateTime::toString()

(the format depends on the precision you want (day, hour, minute, ...)



All Articles