Back

Accessible icon-only buttons in QML

Buttons are a fundamental element in user interfaces, but it’s easy to make some accessibility mistakes when using icon-only buttons in QML.

First, please avoid icon-only buttons and only use then, when the icon is very well known (e.g. arrows, delete or favorite icons) and the space is limited.

In case you still want to use an icon-only button. Make sure to set the text: property and that it is also translatable. Otherwise, a screen reader won’t know that to say about the button. This is because the text: property is used as default value for the Accessible.name: property, so when it is not set Accessible.name is empty and the screen reader can only say that the currently focused control is a button. The trick to have both the text: property set and an icon-only button is to use the display: property and assign it to the AbstractButton.IconOnly.

This gives us the following code:

import QtQuick 2.15
import QtQuick.Controls 2.15

Button {
    text: i18n("Favorite")
    icon.name: 'favorite'
    display: AbstractButton.IconOnly
}

Finally, another essential part is that an icon-only button requires a tooltip. We need the tooltip in case the user is unsure about the meaning of the icon and we need more details.

import QtQuick 2.15
import QtQuick.Controls 2.15

Button {
    text: i18n("Favorite")
    icon.name: 'favorite'
    display: AbstractButton.IconOnly

    ToolTip.text: text
    ToolTip.delay: Kirigami.Units.toolTipDelay
    ToolTip.visible: hovered
}

Note that this used the ToolTip attached property instead of a separate item ToolTip {} as it is more memory efficient. With the attached property, we share the tooltip instance across the entire application instead of instanciating a ToolTip popup for each button.

Comments

With an account on the Fediverse or Mastodon, you can respond to this post. Since Mastodon is decentralized, you can use your existing account hosted by another Mastodon server or compatible platform if you don't have an account on this one. Known non-private replies are displayed below.

Learn how this is implemented here.

Licensed under CC BY-SA 4.0