QML文本元素中的超链接

33

在我的 QML Text 元素中,我想要一个指向网站的超链接,我设法使它看起来像一个超链接等等。但是当我点击或触摸它时,没有任何反应,这个链接应该会在默认浏览器中打开。

Text {
    id: link_Text
    text: '<html><style type="text/css"></style><a href="http://google.com">google</a></html>'
}

你有任何想法我做错了什么吗?


我不知道你做错了什么,但如果其他方法都失败了,在C++中创建一个调用system("xdg-open http://www.google.com")的QML组件。这将在桌面Linux发行版上运行。我不确定Symbian是否适用。请记得包含stdlib以使用system()函数。 - user744186
我花了数小时来调试为什么我的链接无法工作。原来点击区域总是左对齐的,所以如果使用 horizontalAlignment: Text.AlignHCenter,那么蓝色下划线文本和实际链接就会处于不同的位置。 - nwp
3个回答

61

好的,我刚刚发现我需要添加这个:

onLinkActivated: Qt.openUrlExternally(link)

我最初没有考虑过这样的情况,因为我认为如果字符串格式正确,它会自动打开链接。


1
如果在单个文本块中有多个锚点标签,我们如何区分它们?使用ID来实现吗?编辑:糟糕,我们可以查看传递的“link”参数来确定哪个链接被激活了! - Alex Vallejo
2
关于在链接悬停时更改鼠标指针的小添加链接:https://blog.shantanu.io/2015/02/15/creating-working-hyperlinks-in-qtquick-text/ - Piroxiljin

1
如果你想在鼠标悬停时更改光标,可以使用以下组合:
    Text {
        id: link_Text
        text: '<html><style type="text/css"></style><a href="http://google.com">google</a></html>'
        onLinkActivated: Qt.openUrlExternally(link)
        MouseArea {
            id: mouseArea
            anchors.fill: parent
            acceptedButtons: Qt.NoButton // Don't eat the mouse clicks
            cursorShape: Qt.PointingHandCursor
        }
    }

0
我面临着一个模拟超链接的任务:当用户将鼠标悬停在上面时,文本应该看起来像一个超链接。但是当用户点击链接时,应该调用一个自定义处理程序而不是打开URL。也许这对某些人会有用。
Text{
    id: hyperlinkButtonText
    text: "Hyperlink button"
    color: application.primaryColor
    font.pixelSize: 12
    font.bold:true 

    MouseArea{
        id: mouseHyperlinkArea
        anchors.fill: parent
        hoverEnabled: true
        cursorShape: Qt.PointingHandCursor
        onClicked: {
            // to do something on clicking the link
        }
    }            
}
Rectangle{ /*Here is an underline item for the text above*/
    visible: mouseHyperlinkArea.containsMouse
    anchors.top:hyperlinkButtonText.bottom
    anchors.topMargin: -1
    width:hyperlinkButtonText.width
    height: 0.5
    color: application.primaryColor
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接