Using QRect with QHash

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; }[/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 comments to “Using QRect with QHash”

You can leave a reply or Trackback this post.
  1. http://Brandon says: -#1

    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. Good idea! The thought didn’t occur to me. Thanks!