草庐IT

c++ - 如果有的话,有没有办法获得 QColor 的智能名称?

coder 2024-02-16 原文

我按名称(“红色”、“绿色”)创建了一种颜色,但稍后当我询问它的名称时,我得到了 RGB 信息。有没有办法检索颜色名称(如果有的话)(显然,它们不可能都有名称)。

#include <QColor>
#include <iostream>

int main( int argc, char* argv[] )
{
    QColor color( "red" );
    std::cout << color.name().toStdString();
    return 0;
}

这会输出“#ff0000”,我希望它输出“red”。

最佳答案

我从文档中看到的唯一方法是遍历 Qt 知道的所有命名颜色(由 QColor::colorNames() 提供),将每个颜色转换为 QColor并检查颜色是否匹配(operator== 可用 QColor)。

如果您想重复执行此操作,建议使用某种 map 而不是不断地进行线性搜索。 QColor不直接作为映射键(没有 operator< 也没有哈希函数),但我们可以使用它的底层 RGBA 值。如果我们为此编写自定义代码,我们也可以通过避免(出于我们的目的)低效的 map/unordered_map 实现并改用对排序 vector 的二进制搜索来获得正确的性能方面:

// Lookup class that is only accessible from getColorName free function.
class NamedQColorLookup
{
private:
    NamedQColorLookup()
    {
        auto keyList = QColor::colorNames();

        // Simple implementation for filling _keys and _values using std::map.
        // Alternatively, sort two vectors at once, for example like
        // https://stackoverflow.com/questions/17074324/how-can-i-sort-two-vectors-in-the-same-way-with-criteria-that-uses-only-one-of
        // But that's less readable and (since it's only done once) has no meaningful performance impact.
        std::map<std::uint64_t, QString> colorMap;
        for (const auto& key : keyList)
            colorMap.emplace(QColor(key).rgba64(), key);

        // Convert to faster and smaller vector lookup.
        _keys.reserve(colorMap.size());
        _values.reserve(colorMap.size());
        for (const auto& [key, value] : colorMap)
        {
            _keys.emplace_back(key);
            _values.emplace_back(value);
        }
    }

    QString getName(const QColor& color) const
    {
        auto rgba = color.rgba64();
        // Binary search for the RGBA value.
        auto [notLessThan, greaterThan] = std::equal_range(_keys.begin(), _keys.end(), rgba);

        // If this is not a named color, return the RGB code instead.
        if (notLessThan == greaterThan)
            return color.name();

        // We found a matching ARGB value, obtain its index.
        auto index = std::distance(_keys.begin(), notLessThan);
        return _values[index];
    }

    std::vector<std::uint64_t> _keys;
    std::vector<QString> _values; // ...or some kind of string view if you want.

    friend QString getColorName(const QColor& color);
};

// The interface for color -> name lookups.
QString getColorName(const QColor& color)
{
    static NamedQColorLookup lookup;
    return lookup.getName(color);
}

我们可以使用 std::vector<std::pair<std::uint64_t, QString>>而不是两个单独的 vector ,但这会使二进制搜索变慢(更多缓存未命中)。

在这里玩:https://godbolt.org/z/z1fgyc

关于c++ - 如果有的话,有没有办法获得 QColor 的智能名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57491507/

有关c++ - 如果有的话,有没有办法获得 QColor 的智能名称?的更多相关文章

  1. ruby - 难道Lua没有和Ruby的method_missing相媲美的东西吗? - 2

    我好像记得Lua有类似Ruby的method_missing的东西。还是我记错了? 最佳答案 表的metatable的__index和__newindex可以用于与Ruby的method_missing相同的效果。 关于ruby-难道Lua没有和Ruby的method_missing相媲美的东西吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/7732154/

  2. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  3. ruby-on-rails - rails 目前在重启后没有安装 - 2

    我有一个奇怪的问题:我在rvm上安装了ruby​​onrails。一切正常,我可以创建项目。但是在我输入“railsnew”时重新启动后,我有“程序'rails'当前未安装。”。SystemUbuntu12.04ruby-v"1.9.3p194"gemlistactionmailer(3.2.5)actionpack(3.2.5)activemodel(3.2.5)activerecord(3.2.5)activeresource(3.2.5)activesupport(3.2.5)arel(3.0.2)builder(3.0.0)bundler(1.1.4)coffee-rails(

  4. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  5. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  6. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  7. ruby - 如果指定键的值在数组中相同,如何合并哈希 - 2

    我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat

  8. ruby-on-rails - 如果我将 ruby​​ 版本 2.5.1 与 rails 版本 2.3.18 一起使用会怎样? - 2

    如果我使用ruby​​版本2.5.1和Rails版本2.3.18会怎样?我有基于rails2.3.18和ruby​​1.9.2p320构建的rails应用程序,我只想升级ruby的版本,而不是rails,这可能吗?我必须面对哪些挑战? 最佳答案 GitHub维护apublicfork它有针对旧Rails版本的分支,有各种变化,它们一直在运行。有一段时间,他们在较新的Ruby版本上运行较旧的Rails版本,而不是最初支持的版本,因此您可能会发现一些关于需要向后移植的有用提示。不过,他们现在已经有几年没有使用2.3了,所以充其量只能让更

  9. 没有类的 Ruby 方法? - 2

    大家好!我想知道Ruby中未使用语法ClassName.method_name调用的方法是如何工作的。我头脑中的一些是puts、print、gets、chomp。可以在不使用点运算符的情况下调用这些方法。为什么是这样?他们来自哪里?我怎样才能看到这些方法的完整列表? 最佳答案 Kernel中的所有方法都可用于Object类的所有对象或从Object派生的任何类。您可以使用Kernel.instance_methods列出它们。 关于没有类的Ruby方法?,我们在StackOverflow

  10. ruby-on-rails - Rails 3,嵌套资源,没有路由匹配 [PUT] - 2

    我真的为这个而疯狂。我一直在搜索答案并尝试我找到的所有内容,包括相关问题和stackoverflow上的答案,但仍然无法正常工作。我正在使用嵌套资源,但无法使表单正常工作。我总是遇到错误,例如没有路线匹配[PUT]"/galleries/1/photos"表格在这里:/galleries/1/photos/1/edit路线.rbresources:galleriesdoresources:photosendresources:galleriesresources:photos照片Controller.rbdefnew@gallery=Gallery.find(params[:galle

随机推荐