QColor does not provide a hash function for QSet or std::unordered_set by default. You can add that locally (or globally for your program) though by delegating that to the hash function for QRgb (which includes alpha value as well):
#include <QColor>
#include <QDebug>
#include <QSet>
#include <unordered_set>
// hash function for QColor for use in QSet / QHash
QT_BEGIN_NAMESPACE
uint qHash(const QColor &c)
{
return qHash(c.rgba());
}
QT_END_NAMESPACE
// hash function for QColor for std::unordered_set
namespace std {
template<> struct hash<QColor>
{
using argument_type = QColor;
using result_type = size_t;
result_type operator()(const argument_type &c) const
{
return hash<QRgb>()(c.rgba());
}
};
} // namespace std
int main(int argc, char *argv[])
{
QSet<QColor> qs;
qs.insert(QColor(100, 100, 100));
qs.insert(QColor(100, 100, 100));
qs.insert(QColor(50, 100, 100));
qDebug() << qs.size() << qs.toList();
std::unordered_set<QColor> ss;
ss.insert(QColor(100, 100, 100));
ss.insert(QColor(100, 100, 100));
ss.insert(QColor(50, 100, 100));
qDebug() << ss.size();
for (auto c : ss)
qDebug() << c;
return 0;
}
Or you can also not put the QColors into the set, but the QRgb values (via QColor::rgba()), and later convert them back to QColor via the QColor(QRgb) constructor again.
QColor
does not provide a hash function forQSet
orstd::unordered_set
by default. You can add that locally (or globally for your program) though by delegating that to the hash function for QRgb (which includes alpha value as well):Or you can also not put the
QColor
s into the set, but theQRgb
values (viaQColor::rgba()
), and later convert them back toQColor
via theQColor(QRgb)
constructor again.