Creating working hyperlinks in Qt Quick Text

These days its fairly common that your UI designer walks up to you and asks to include web-style links in your desktop app.
Thanks to the fact that Qt Quick Text element supports HTML, you can say-

Text {
    anchors.centerIn: parent
    text: "To learn about KDE, <a href='http://www.kde.org'>click here</a>"
}

which results in-

Screenshot

Notice how nothing happens when you click on the link? This is because Qt Quick doesn’t open a browser by default, but lets you decide what to do by emitting the linkActivated signal which you can handle-

Text {
    anchors.centerIn: parent
    text: "To learn about KDE, <a href='http://www.kde.org'>click here</a>"
    onLinkActivated: Qt.openUrlExternally(link)
}

The link works now, but there’s another problem: you don’t see a hand cursor when hovering over the link. This is going to cause quite some confusion for your user. To fix this, use the following-

Text {
    anchors.centerIn: parent
    text: "To learn about KDE, <a href='http://www.kde.org'>click here</a>"
    onLinkActivated: Qt.openUrlExternally(link)

    MouseArea {
        anchors.fill: parent
        acceptedButtons: Qt.NoButton // we don't want to eat clicks on the Text
        cursorShape: parent.hoveredLink ? Qt.PointingHandCursor : Qt.ArrowCursor
    }
}

Screenshot

Presto! You get a link with the correct hand cursor in Qt Quick.

Advertisements

3 thoughts on “Creating working hyperlinks in Qt Quick Text

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s