Is it possible to store QColor in a QMap as key

1.8k Views Asked by At

So, I have simple code

QMap<QColor, int> colors;
for(int w = 0; w < image.width(); ++w)
    for (int h = 0; h < image.height(); ++h)
        colors[QColor::fromRgb(image.pixel(w,h))]++;

The error message is

no match for 'operator<' (operand types are 'const QColor' and 'const QColor').

So, qMapLessThanKey is trying unsuccessfully to instantiate comparer of two colors and it's impossible.

Question is: Is it possible to store QColor in a QMap as key as value and not by reference?

Just curious. I know how to write what I want in other way. But it looks for me strange that there is any exceptions in QT on what I can store in map or cannot.

2

There are 2 best solutions below

5
On BEST ANSWER

No, because QColor doesn't provide operator<, which is required by QMap's Key type:

The key type of a QMap must provide operator<() specifying a total order.

An option would be to define operator< for QColor yourself, but I wouldn't advise it, as I'm not sure it's supposed to be defined.

I would recommend just to use std::map with a custom comparator (the third template argument) along the lines of:

struct color_compare {
    bool operator()(QColor const&, QColor const&) { /* ... */ }
};

std::map<QColor, Value, color_compare> map;
// ...
2
On

Sure, it's possible. This is a missing Qt feature. You can implement the comparison operator yourself, comparing the R,G,B,A values lexicographically:

// https://github.com/KubaO/stackoverflown/tree/master/questions/qmap-qcolor-32512125
#include <QtGui>

bool operator<(const QColor & a, const QColor & b) {
   return a.redF() < b.redF()
       || a.greenF() < b.greenF()
       || a.blueF() < b.blueF()
       || a.alphaF() < b.alphaF();
}

int main() {
   Q_ASSERT(QColor(Qt::blue) < QColor(Qt::red));
   Q_ASSERT(QColor(Qt::green) < QColor(Qt::red));
   Q_ASSERT(QColor(Qt::blue) < QColor(Qt::green));
   Q_ASSERT(! (QColor(Qt::red) < QColor(Qt::red)));
   QMap<QColor, int> map;
   map.insert(Qt::red, 0);
   map.insert(Qt::green, 1);
   map.insert(Qt::blue, 2);
   Q_ASSERT(map.size() == 3);
   Q_ASSERT(map.cbegin().key() == Qt::red);
   Q_ASSERT((map.cbegin()+1).key() == Qt::green);
   Q_ASSERT((map.cbegin()+2).key() == Qt::blue);
}