如何为QML TextEdit设置圆角背景?RichText样式border-radius无效
QML TextEdit圆角背景设置方案
你遇到的问题是因为QML的RichText对CSS的支持有限,border-radius这类属性不在它支持的CSS子集里,所以直接在<span>里设置不会生效。下面给两种可行的解决方法:
方法一:用外层Rectangle做背景
给TextEdit套一个带圆角的Rectangle作为背景,同时把TextEdit的默认背景设为透明:
Rectangle { // 宽高根据TextEdit内容调整,或者绑定TextEdit的尺寸加内边距 width: textEdit.contentWidth + 10 height: textEdit.contentHeight + 10 radius: 20 color: "grey" TextEdit { id: textEdit anchors.centerIn: parent textFormat: TextEdit.RichText text: "<span style=\"color:blue;font-weight:bold\">blue</span>" // 取消默认背景 background: TransparentRectangle {} } }
方法二:直接设置TextEdit的background属性(Qt Quick Controls 2)
如果使用的是Qt Quick Controls 2的TextEdit,可以直接替换它的background为带圆角的Rectangle:
TextEdit { id: textEdit textFormat: TextEdit.RichText text: "<span style=\"color:blue;font-weight:bold\">blue</span>" // 自定义背景 background: Rectangle { color: "grey" radius: 20 } padding: 5 // 加内边距让文字和圆角背景之间有间距 }
内容的提问来源于stack exchange,提问作者isudfv
相关产品推荐
相关产品推荐

