本页内容

图标在Qt Quick Controls

在Qt Quick Controls 中,按钮、项目委托和菜单项除了文本标签外,还可以显示图标。

使用图标

AbstractButton 和Action 提供了以下属性,可用于设置图标:

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

主题图标通过名称引用,普通图标则通过源 URL 引用。可同时设置 `icon.name ` 和 `icon.source `,以确保始终能找到图标。如果图标在主题中找到,则始终使用该图标;即使同时设置了 `icon.source ` 也是如此。如果图标在主题中未找到,则改用 `icon.source `。

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

每种Qt Quick Controls 2 样式都会根据其规范请求默认图标大小和颜色,但可以通过设置icon.width 、icon.height 和icon.color 属性来覆盖这些设置。

对于未设置 `width ` 和 `height ` 的图标,其加载的图像取决于所使用的图标类型。对于主题图标,系统将选择最接近的可用尺寸;对于普通图标,其行为与 `Image` 的 `sourceSize ` 属性相同。

图标颜色默认设置为与不同状态下的文本颜色相匹配。若要使用原始颜色的图标,请将颜色设置为"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 Demo提供了带有内置图标主题的完整可运行应用程序。

© 2026 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.