我有一个 TextArea 组件,其中包含富文本内容,其中还包含链接。当我将鼠标悬停在链接上时,我想更改其背景。
我知道我可以使用类似于 css 的语法来更改文本文档中的样式,例如通过向其内容添加样式标签,并且伪类 :hover 在 QML 中不起作用。 我还尝试了向文本区域添加矩形的方法,并试图找到一种将其放在文本后面的方法。我尝试使用 z 属性,但这不起作用。另外,我无法准确确定悬停链接的位置来相应地定位矩形。
所以我的问题是如何向更改其背景的链接添加悬停效果?
到目前为止我的(仍然不完整)代码:
import QtQuick 6.5
import QtQuick.Controls 6.5
import QtQuick.Layouts 6.5
Rectangle {
color: "#555"
anchors.fill: parent
RowLayout
{
TextArea {
Rectangle {
id: linkHoverBackground
width: 100
height: 30
color: "#050"
z: 0
}
Layout.fillWidth: true
Layout.fillHeight: true
z: 1
text: "<style type=\"text/css\">a { color: #090; } a:hover { color: #900; }</style>" +
"<h3>TextArea Element:</h3>" +
"Hier ein <a href=\"https://www.google.com\">Testlink</a><br>" +
"Und hier noch ein <a href=\"https://www.google.com\">Testlink</a> mit Text dahinter"
color: "#ddd"
textFormat: TextEdit.RichText
//styleSheet: "a { color: #090; }" -> error, prop doesnt exist
MouseArea
{
id: mouseArea
anchors.fill: parent
acceptedButtons: Qt.NoButton // Don't eat the mouse clicks
cursorShape: Qt.PointingHandCursor
onPositionChanged: function(e)
{
console.log(e.x, e.y)
linkHoverBackground.x = e.x
linkHoverBackground.y = e.y
}
}
}
}
}
只要鼠标滑过链接,就会设置/取消设置
hoveredLink
属性。您可以使用它来填充您自己的 linkColor
和 linkBackgroundColor
。通过这样做,您可以使用一些创造性的字符串插值来相应地设置 HTML
格式:
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
Page {
ColumnLayout {
TextAreaLink {
text: `<h3>TextArea Element:</h3>`
}
TextAreaLink {
text: `<style type="text/css">a { color: ${linkColor}; background-color: ${linkBackgroundColor} }</style>Hier ein <a href="https://www.google.com">Testlink</a>`
}
TextAreaLink {
text: `<style type="text/css">a { color: ${linkColor}; background-color: ${linkBackgroundColor} }</style>Und hier noch ein <a href=\"https://www.google.com\">Testlink</a> mit Text dahinter</a>`
}
}
}
// TextAreaLink.qml
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
TextArea {
property color linkColor: hoveredLink ? "yellow" : "green"
property color linkBackgroundColor: hoveredLink ? "steelblue" : "transparent"
textFormat: TextEdit.RichText
color: "#ddd"
HoverHandler {
enabled: parent.hoveredLink
cursorShape: Qt.PointingHandCursor
}
onLinkActivated:
(link) =>
console.log('Link activated to: `' + link + '`')
}
您可以在线尝试!