如何使 QML `Text` 元素中的链接在悬停时显示手形鼠标光标?

问题描述 投票:0回答:1

在网络浏览器中,当您将鼠标悬停在链接上时,它会变为指向手。我想在 QML 中实现同样的目标。

这是一个 QML

Text
元素,其中包含使用 HTML 标记的文本块,其中包括几个链接:

Text { id: bodyMessage
   anchors.fill: parent
   textFormat: Text.RichText
   wrapMode: Text.WordWrap

   text:
      '<p>' + qsTr('Here is my first paragraph.') + '</p>' +
      '<p>' + qsTr('My second paragraph contains the <a href="link1">first link</a>.') + '</p>' +
      '<p>' + qsTr('My third paragraph contains the <a href="link2">second link</a> and that is it.') + '</p>'

   onLinkActivated:
      (link) =>
      console.log('Link activated to: `' + link + '`')
}

问题在于,当鼠标光标位于任一链接上方时,鼠标光标不会更改为指针。

我尝试了一个孩子

MouseArea
如下:

   MouseArea {
      anchors.fill: parent
      hoverEnabled: true

      onPositionChanged:
         (mouse) =>
         cursorShape = bodyMessage.linkAt(mouse.x, mouse.y) ? Qt.PointingHandCursor : Qt.ArrowCursor
   }

这确实可以让鼠标光标根据需要进行更改,但它会阻止鼠标信号发送到

Text
,因此
onLinkActivated
不再起作用。

为了解决这个新问题,我将以下内容添加到

MouseArea

                onClicked:
                    (mouse) =>
                    {
                        let link = bodyMessage.linkAt(mouse.x, mouse.y)
                        if (link.length > 0)
                            console.log('Link activated to: `' + link + '`')
                    }

虽然这确实有效,但它使

Text.linkActivated
变得过时,在我看来这是错误的方法,而且代码对我来说看起来很臃肿。

html css qt hyperlink qml
1个回答
1
投票

您可以考虑在您的

HoverHandler
中添加
Text
:

HoverHandler {
    enabled: bodyMessage.hoveredLink
    cursorShape: Qt.PointingHandCursor
}

这是一个完整的工作示例:

import QtQuick
import QtQuick.Controls
Page {
    title: "HoverHandler Demo"
    Text { id: bodyMessage
        anchors.fill: parent
        textFormat: Text.RichText
        wrapMode: Text.WordWrap
        
        text:
        '<style>' +
        '  a:link { color: red; text-decoration: underline; }' +
        '  a:hover { color: purple; }' +
        '  a:active { color: blue; }' +
        '</style>' +
        '<p>' + qsTr('Here is my first paragraph.') + '</p>' +
        '<p>' + qsTr('My second paragraph contains the <a href="https://stackoverflow.com"> StackOverflow link</a>.') + '</p>' +
        '<p>' + qsTr('My third paragraph contains the <a href="https://www.google.com">Google link</a> and that is it.') + '</p>'
        
        HoverHandler {
            enabled: bodyMessage.hoveredLink
            cursorShape: Qt.PointingHandCursor
        }
        
        onLinkActivated: {
            console.log('Link activated to: `' + link + '`');
            Qt.openUrlExternally(link);
        }
    }
}

您可以在线尝试!

参考资料:

© www.soinside.com 2019 - 2024. All rights reserved.