QML 自定义Button样式,实现按钮三态切换

初学QML的时候,遇到了一些问题,参考这篇文章,实现了按钮的正常、鼠标经过和鼠标按下的图片切换。遇到了一些问题,比如背景色有白边,设置图片大小不生效。尝试了几种方法后,还是发现原来的方法比较好。记录一下自己改良后的代码:

import QtQuick 2.0
import QtQuick.Controls 1.4
import QtQuick.Controls.Styles 1.4

Button
{
    id: root_Button
    property string nomerPic: "qrc:/images/login_normal.png"
    property string hoverPic: "qrc:/images/login_hover.png"
    property string pressPic: "qrc:/images/login_pressed.png"

    style: ButtonStyle {
        background:Rectangle{
            implicitHeight: root_Button.height
            implicitWidth:  root_Button.width

            color: "transparent"  //设置背景透明,否则会出现默认的白色背景

            BorderImage{
                anchors.fill: parent
                source: control.hovered ? (control.pressed ? pressPic : hoverPic) : nomerPic;
            }
        }
    }
}

参考:https://blog.csdn.net/z609932088/article/details/70500029

要在QML实现多页的切换,可以使用`StackView`组件和按钮实现。`StackView`用于管理多个页面,并提供了一种简单的方式来切换页面。 以下是一个示例代码,展示了如何使用按钮切换多个页面: ```qml import QtQuick 2.0 import QtQuick.Controls 2.15 import QtQuick.Layouts 1.15 ApplicationWindow { visible: true width: 400 height: 300 StackView { id: stackView anchors.fill: parent initialItem: page1 Component.onCompleted: { stackView.push(page1); // 初始页面 } } RowLayout { anchors.bottom: parent.bottom spacing: 10 Button { text: "Page 1" onClicked: stackView.push(page1) } Button { text: "Page 2" onClicked: stackView.push(page2) } Button { text: "Page 3" onClicked: stackView.push(page3) } } Component { id: page1 Rectangle { width: stackView.width height: stackView.height color: "lightblue" Text { text: "Page 1" font.pixelSize: 20 anchors.centerIn: parent } } } Component { id: page2 Rectangle { width: stackView.width height: stackView.height color: "lightgreen" Text { text: "Page 2" font.pixelSize: 20 anchors.centerIn: parent } } } Component { id: page3 Rectangle { width: stackView.width height: stackView.height color: "lightpink" Text { text: "Page 3" font.pixelSize: 20 anchors.centerIn: parent } } } } ``` 在上面的例子,我们使用`StackView`作为主要的页面管理器,并在底部使用`RowLayout`来放置按钮。 每个按钮都有一个`onClicked`事件处理程序,当按钮被点击时,我们使用`stackView.push()`函数将相应的页面推入`StackView`。 每个页面都是通过`Component`定义的,其包含一个带有文本的矩形。你可以根据需要自定义页面的内容和样式。 通过点击按钮,你可以在应用程序切换不同的页面。这种方式可以用于创建多页应用程序、导航界面等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值