Using QRect with QHash

January 17th, 2008

In Qt 4.3.3, I found myself needing to use QRect instances as a key in a QHash. However, Trolltech provides no qHash() implementation for QRect, so I implemented this one, and I think it ought to cover the most common uses of QRect. What do you think?

uint qHash(const QRect &rect)
{
    uint code = 0;

    code |= (rect.x() < < 16);
    code |= (rect.y() & 0x0000ffff);
    code ^= (rect.width() << 16);
    code ^= (rect.height() & 0x0000ffff);

    return code;
}

Preliminary testing seems indicates that it produces a fairly good distribution of hash codes. In this case, I’m defining “fairly good” as, “I haven’t seen any collisions on the few rectangles I’ve tried.” :)

2 Responses to “Using QRect with QHash”

  1. Brandon Says:

    If you trust Sun you could probably use the hash implementation they use in the JVM, they usually go through a fair amount of work to ensure that they have a decent algorithm that minimizes collisions. Not sure about licensing though. Their hash is basically x + 37*y + 43*width + 47*height.

  2. Dave Says:

    Good idea! The thought didn’t occur to me. Thanks!

Leave a Reply