如何在qml文本中设置工具提示

nph*_*pht 1 qt qml

当我将鼠标悬停在 qml 文本中的某些单词时,是否有某种方法可以显示提示?例如,我想查看我在文本中悬停的单词的定义。

*维基百科网站有此功能。

Mit*_*tch 5

要允许将鼠标悬停在单个单词上,您可以使用以下代码:

import QtQuick
import QtQuick.Controls

ApplicationWindow {
    title: qsTr("Hello World")
    width: 640
    height: 480
    visible: true

    HoverHandler {
        id: hoverHandler
        onHoveredChanged: {
            if (hovered)
                toolTip.hide()
        }
    }

    Label {
        id: label
        anchors.fill: parent
        text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud <a href=\"Definition goes here\">exercitation</a> ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu <a href=\"Definition goes here\">fugiat</a> nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
        wrapMode: Label.Wrap

        onLinkHovered: (link) => {
            if (link.length === 0)
                return

            // Show the ToolTip at the mouse cursor, plus some margins so the mouse doesn't get in the way.
            toolTip.x = hoverHandler.point.position.x + 8
            toolTip.y = hoverHandler.point.position.y + 8
            toolTip.show(link)
        }
    }

    ToolTip {
        id: toolTip
    }
}
Run Code Online (Sandbox Code Playgroud)

它使用 Text 的linkHovered信号来响应悬停的链接,并使用HoverHandler确保当链接未悬停时工具提示隐藏。您还可以向show()传递一个超时,以在一段时间后隐藏工具提示,但这对用户不太友好。

工具提示的屏幕录制

GIF 中使用的样式是Material 样式