QT qml给控件添加任意一条边框

本文介绍在Qt的QML中如何使用Control类型的background属性来自定义元素的背景和边框,通过两种方法实现任意方向的边框效果:一是使用叠加的Rectangle,二是使用Shape绘制边框线。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Qt的qml的Control类型有个background属性,使用这个属性可以自己绘制背景,从而达到可以设置任意方向的边框

我找到两个方法

方法一:使用两个Rectangle进行覆盖

Page {
        id: page
        x: 200
        y: 78
        width: 200
        height: 200

        background: Rectangle {
            anchors.fill: parent
            color: "white"
            border.width: 1
            border.color: "black"

            // 使用矩形覆盖上层Rectangle的边框
            Rectangle {
                color: parent.color
                border.width: 0
                anchors.fill: parent
                // 使用Margin来确定是否显示边框
                anchors.leftMargin: 1
                anchors.topMargin: 1
                anchors.rightMargin: 1
                anchors.bottomMargin: 0
            }
        }
    }

效果如下图:

方法二:使用Shape绘制边框线

Page {
        id: pageID
        x: 200
        y: 78
        width: 200
        height: 200

        background: Rectangle {
            anchors.fill: parent
            color: "white"
            border.width: 0
            border.color: "black"
            // 绘制一条边框
            Shape {
                anchors.fill: parent
                ShapePath {
                    strokeWidth: 0
                    strokeColor: "black"
                    strokeStyle: ShapePath.SolidLine
                    startX: 0
                    startY: 0
                    PathLine {
                        x: pageID.width
                        y: 0
                    }
                    PathLine {
                        x: pageID.width
                        y: pageID.height
                    }
                }
            }
        }
    }

效果如图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值