QColor into list for later retrieval

462 views Asked by At

I want to add all the selected colors into a list without duplicate entry and later all the selected colors should popup in a widget.

How can I add QColor into list and later extract it

1

There are 1 answers

0
E4z9 On BEST ANSWER

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.