环境:
Ubuntu16.04 + Qt5.7.1
描述:
实现一个经常会遇到的功能:侧边弹窗。不得不说用QMl实现十分方便快捷,简单明了。
效果图如下:
代码解释:
主要解释一下qml代码,main.qml代码如下:
import QtQuick 2.5
import QtQuick.Controls 1.4
Rectangle {//主界面
width: 640
height: 480
property bool sideWindShow: false //记录按键状态
Text {
text: qsTr("我是主界面")
anchors.centerIn: parent
}
Rectangle {
id: sideWin
color: "#7709abcd" //77代表半透明状态,如果希望窗口弹出时为不透明则使用ff
x: 0 - width //这是弹窗的位置坐标,此处的做法是将弹窗隐藏在主界面的左侧
width: parent.width * 0.8 //弹窗的大小
height: parent.height
Text {
text: qsTr("hhhhhh我出来了")
anchors.centerIn: parent
}
//这是弹窗弹出的效果,相比C++实现的动态效果,这里显得十分“轻巧”;看字面的意思也可以猜测出是弹窗横坐标发生变化时的行为
Behavior on x {
NumberAnimation { //一个动画的类型,具体可以查看一下qt助手,本人也是在学习中
duration: 300 //动画持续时间,以ms计算
}
}
}
Rectangle { //弹窗的“按钮”,此处是因为使用了图标所以用Rectangle来实现
id: popUpBtn
color: "#00000000" //设置此”按钮“为全透明
width: 64
height: 64
anchors.left: sideWin.right //此处的锚布局设置为弹窗的右侧
anchors.verticalCenter: sideWin.verticalCenter //锚布局为弹窗的垂直中线上
Image {
anchors.centerIn: parent
source: "qrc:/images/out_arrow.png"
MouseArea { //此处是实现点击的关键(所以说Qml中很多时候不会直接使用Button,因为通过自己的样式选择可以轻易实现”按钮“功能)
anchors.fill: parent
onPressed: {
popUpBtn.color = "#ff40598a" // 此处是为了体现”按钮“点击时的背景效果
}
onReleased: {
popUpBtn.color = "#00000000" // 恢复按钮未被按下时的背景效果
}
onClicked: {
sideWindShow = !sideWindShow
// 三目运算符的用法,在此处改变弹窗的位置坐标,此时弹窗的行为即会触发出现动态效果
sideWindShow ? sideWin.x = 0 : sideWin.x = 0 - sideWin.width
sideWindShow ? parent.source = "qrc:/images/in_arrow.png" : parent.source = "qrc:/images/out_arrow.png"
}
}
}
}
}
整体来说这样弹窗的效果并不难实现。本人亦是初学者,与大家共同学习。