如何使 QML `Text` 元素中的链接表现得像 Web 浏览器中的链接?

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

在 Web 浏览器中,您可以设置 HTML 链接的样式以指示悬停和活动,并且当您将鼠标悬停在链接上时,它会变为指向手。我想在 QML 中实现同样的目标。

这是一个 QML

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

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="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 + '`')
}

我遇到的问题是:

  1. 虽然样式
    a:link
    应用于链接,但
    a:hover
    a:active
    都没有应用。
  2. 当鼠标光标位于链接上方时,鼠标光标不会变为指针。

为了解决第二个问题,我尝试了一个孩子

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 hyperlink qml
1个回答
0
投票

将此添加到您的

Text

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

https://doc.qt.io/qt-6/qml-qtquick-hoverhandler.html

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