首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否可以将QColor作为密钥存储在QMap中

是否可以将QColor作为密钥存储在QMap中
EN

Stack Overflow用户
提问于 2015-09-10 21:44:04
回答 2查看 1.6K关注 0票数 3

所以,我有简单的代码

代码语言:javascript
复制
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))]++;

错误信息是

不匹配“operator<”(操作数类型为“const QColor”和“const QColor”)。

因此,qMapLessThanKey试图实例化两种颜色的比较器,但没有成功,这是不可能的。

的问题是:是否可以将QColor作为值而不是引用存储在QMap中?

只是好奇而已。我知道怎么用另一种方式写我想要的东西。但让我感到奇怪的是,QT中有任何例外,我可以存储在地图中,或者不能存储。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-09-10 21:54:42

不,因为operator<QMapKey类型的必填项

QMap的键类型必须提供指定总顺序的operator<()

一种选择是自己为operator<定义QColor,但我不建议它,因为我不确定它是否应该被定义。

我建议只对自定义比较器(第三个模板参数)使用std::map,如下所示:

代码语言:javascript
复制
struct color_compare {
    bool operator()(QColor const&, QColor const&) { /* ... */ }
};

std::map<QColor, Value, color_compare> map;
// ...
票数 5
EN

Stack Overflow用户

发布于 2015-09-11 14:15:25

当然有可能。这是一个缺少的Qt特性。您可以自己实现比较操作符,按字典顺序比较R、G、B、A值:

代码语言:javascript
复制
// 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);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32512125

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档