通常我们将用户界面描述为一种状态。一个状态定义了一组属性的改变,并且会在一定的条件下被触发。
Demo
通过一个按钮(button)来控制切换另外两个按钮的状态(出现/隐藏)。
- 无图无真相
按钮出现状态
- 按钮状态
- 上代码(cv就能用)
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.13 //控制
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
Rectangle{ //矩形
id:root
state: "true" //初始状态 这里的"true",是下面 State 中定义的 name ,这就是调用
//注意:在一个状态中,只需要描述属性如何从它们的默认状态改变(而不是前一个状态的改变)
states: [
State {
name: "false" //定义此状态名称为"false"
PropertyChanges { target: button1; visible:true } //target:目标 visible:可见
PropertyChanges { target: button2; visible:true }
},
State {
name: "true"
PropertyChanges { target: button1; visible:false }
PropertyChanges { target: button2; visible:false }
}
]
}
Button{ //用Button 就要添加 import QtQuick.Controls 2.13
id: button1
text: qsTr("出现")
width: 60
height: 40
anchors.centerIn:parent //锚点.居中:父类
onClicked: {
}
}
Button{
id: button2
text: qsTr("出现2")
width: 60
height: 40
anchors.top:button1.bottom
anchors.topMargin:8
anchors.horizontalCenter: button1.horizontalCenter
onClicked: {
}
}
Button{
id: button
text: qsTr("控制")
width: 60
height: 40
anchors.top:parent.top
anchors.topMargin:100
anchors.left:parent.left
anchors.leftMargin:120
onClicked: { //点击了
switch (root.state)
{
//状态跳转 //下面的"true"和"false",都是 State 中定义的 name ,这就是调用
case "true": //出现
root.state = "false";
break;
case "false": //隐藏
root.state = "true";
break;
default: break;
}
}
}
}