图标Qt Quick Controls

Qt Quick Controls 自 Qt 5.10 起支持图标。这意味着,除了文本标签外,按钮、项目委托和菜单项现在还能显示图标。

使用图标

AbstractButton 和 提供了以下属性,通过这些属性可以设置图标:Action

  • icon.name
  • icon.source
  • icon.width
  • icon.height
  • icon.color
  • icon.cache

主题图标通过名称引用,普通图标通过源 URL 引用。可同时设置icon.nameicon.source ,以确保始终能找到图标。如果在主题中找到了图标,则将始终使用该图标;即使也设置了icon.source 。如果在主题中找不到图标,icon.source 将被使用。

Button {
    icon.name: "edit-cut"
    icon.source: "images/cut.png"
}

每个Qt Quick Controls 2 样式都会根据其指南要求默认的图标大小和颜色,但可以通过设置icon.widthicon.heighticon.color 属性来覆盖这些属性。

未设置widthheight 的图标所加载的图像取决于所使用的图标类型。对于主题图标,将选择最接近的可用尺寸。对于普通图标,其行为与ImagesourceSize 属性相同。

默认情况下,图标颜色与不同状态下的文本颜色一致。要使用带有原始颜色的图标,请将颜色设置为"transparent"

Button {
    icon.color: "transparent"
    icon.source: "images/logo.png"
}

对于按钮,display 属性可用于控制按钮内图标和文本的显示方式。

icon.cache 属性可控制是否缓存图标图像。更多信息,请参阅cache

图标主题

符合要求的图标主题必须遵循 freedesktop 图标主题规范,可从此处获取:http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-latest.html。

传统上,只有 Linux 和 UNIX 支持平台级图标主题,但也可以在应用程序中捆绑符合要求的图标主题,以便在任何平台上使用主题图标。

默认的icon theme search paths 取决于平台。在 Linux 和 UNIX 上,搜索路径将使用XDG_DATA_DIRS 环境变量(如果可用)。所有平台都有资源目录:/icons 作为备用。自定义图标主题搜索路径可通过QIcon::setThemeSearchPaths() 设置。

下面的示例使用Qt 的资源系统将名为mytheme的图标主题捆绑到应用程序的资源中。

<RCC>
    <qresource prefix="/">
        <file>icons/mytheme/index.theme</file>
        <file>icons/mytheme/32x32/myicon.png</file>
        <file>icons/mytheme/32x32@2/myicon.png</file>
    </qresource>
</RCC>

index.theme 文件描述了图标主题的一般属性,并列出了可用的主题图标目录:

[Icon Theme]
Name=mytheme
Comment=My Icon Theme

Directories=32x32,32x32@2

[32x32]
Size=32
Type=Fixed

[32x32@2]
Size=32
Scale=2
Type=Fixed

为了使用捆绑的图标主题,应用程序应在加载主 QML 文件前调用QIcon::setThemeName() :

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QIcon>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QIcon::setThemeName("mytheme"); // <--

    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    return app.exec();
}

现在,可以使用捆绑图标主题中已命名的图标,而无需指定任何后备源:

Button {
    icon.name: "myicon"
}

Gallery 示例Wearable 演示提供了带有捆绑图标主题的完整可运行应用程序。

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.