2
有人可以幫助我理解此代碼的行爲嗎?我寫了一個簡單的側面菜單示例(現在只是模板),並且使用onMenuVisibleChanged插槽有問題(但我需要的實際工作,只是想了解爲什麼另一種方式不需要)。從邏輯上講,它應該將面板矩形的x更改爲指定值,但不是。請幫我理解這件事的正確方法。QtQuick 2 - 側面板示例
main.qml
import QtQuick 2.3
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2
ApplicationWindow {
title: qsTr("Hello World")
width: 640
height: 480
visible: true
menuBar: MenuBar{
Menu{
title: "File"
MenuItem{
text: "Exit"
onTriggered: Qt.quit()
}
}
}
SidePane{
id: sidePane
menuWidth: 350
z: 2
}
}
SidePane.qml
import QtQuick 2.3
import QtQuick.Window 2.2
Item {
id: screenItem
anchors.fill: parent
function show() {
rect.x = 0
menuVisible = true
}
function hide() {
rect.x = -rect.width
menuVisible = false
}
property int animationDuration: 200
property bool menuVisible: false
property int dragThreshold: 120
property int menuWidth: 300
Rectangle {
id: rect
width: menuWidth
x: -rect.width
height: Screen.height
color: "lightsteelblue"
Drag.active: menuDragArea.drag.active
Behavior on x {
NumberAnimation {
duration: animationDuration
easing.type: Easing.InOutQuad
}
}
MouseArea {
property int dragX: 0
property int startX: 0
property int diffX: 0
id: menuDragArea
hoverEnabled: true
height: rect.height
width: rect.width + 40
anchors.left: rect.left
drag.target: rect
drag.axis: Drag.XAxis
drag.minimumX: -rect.width
drag.maximumX: 0
onPressed: startX = rect.x + rect.width
onReleased: {
dragX = rect.x + rect.width
diffX = Math.abs(startX - dragX)
if ((diffX > dragThreshold) && (startX == 0)){
rect.x = 0
menuVisible = true
} else if ((diffX < dragThreshold) && (startX == 0)){
rect.x = -rect.width
menuVisible = false
}
if ((diffX > dragThreshold) && (startX == rect.width)){
rect.x = -rect.width
menuVisible = false
} else if ((diffX < dragThreshold) && (startX == rect.width)){
rect.x = 0
menuVisible = true
}
}
}
}
Rectangle{
id: shadowRect
anchors.left: rect.right
anchors.right: screenItem.right
opacity: (rect.x + rect.width)/(rect.width * 2.2)
color: "black"
height: screenItem.height
MouseArea{
id: shadowArea
anchors.fill: shadowRect
visible: menuVisible ? true : false
hoverEnabled: true
onClicked: {
if (menuVisible == true){
rect.x = -rect.width
menuVisible = false
}
}
}
Rectangle{
id: shadowRect2
color: "black"
anchors.left: parent.left
width: 5
opacity: (rect.x + rect.width)/(rect.width * 2)
height: screenItem.height
}
Rectangle{
id: shadowRect3
color: "black"
anchors.left: parent.left
width: 3
opacity: (rect.x + rect.width)/(rect.width * 1.9)
height: screenItem.height
}
}
onMenuVisibleChanged: menuVisible ? rect.x = 0 : rect.x = -rect.width
}
得到任何幫助。只是一個QML初學者。最大的目的是在android應用程序中使用這個面板。如果您願意,請隨意使用此代碼。
感謝您的回覆。你什麼意思是可拖動的?我添加了代碼片段以顯示rect.x和mouseX值,當我拖動矩形時,我在屏幕座標上看到它的x值的正確位置。片段是:console.log(「onPressed:mouseX」+ mouseX)和console.log(「onPressed:rect.x」+ rect.x)。除此之外,我只在鼠標區域看到mouseX。 – user3417815
我嘗試重新實現mouseArea。它回答你的問題嗎? – siusiulala
酷,感謝分享代碼片段,我會盡快嘗試它 – user3417815