我有一个包含矩形的 QML 代码。我希望矩形在按下鼠标左键时保持其当前颜色,并在释放按钮时返回其原始颜色。
我尝试添加一个 MouseArea 来检测何时按下按钮并更改矩形的颜色,但这会破坏矩形的原始颜色。如何修改我的代码以在按下鼠标左键时保持矩形的当前颜色并在释放按钮时返回原始颜色?
这是我当前的代码:
import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
ApplicationWindow {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
property string defaultColor: "#444"
GridLayout{
anchors.fill: parent
columns: 2
rows: 2
Repeater{
model: 6
delegate: Rectangle{
color: defaultColor
Layout.fillWidth: true
Layout.fillHeight: true
Text {
id: name
text: modelData
anchors.fill: parent
color: "#eee"
font.pixelSize: 40
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
}
MouseArea{
anchors.fill: parent
acceptedButtons: Qt.RightButton | Qt.LeftButton
onPressed: {
parent.color = this.pressedButtons === Qt.LeftButton ? "orange" : defaultColor
}
}
MouseArea{
anchors.fill: parent
acceptedButtons: Qt.NoButton
hoverEnabled: true
onEntered: parent.color = 'orange'
}
}
}
}
}
非常感谢任何帮助,谢谢!
我希望你继续绘制我的鼠标进入的单元格,但是单击左键这里是 excel 中的一个类似的例子
Rectangle {
id: rectBtn; width: 100; height: 40
color: mouseArea.pressed ? "gray" : "orange";
Text {anchors.centerIn: parent;text: qsTr("Click")}
MouseArea {id: mouseArea;anchors.fill: parent}
}
// ++++++++++ 或 ++++++++++++++++++
Button {
text: "Click"; width: 100; height: 40
background: Rectangle {
anchors.fill: parent
color: parent.down ? "gray" : "orange";
}
}
这段代码的作用和第一张图一样,点击控件后颜色发生变化,鼠标离开控件后颜色保持不变,再次点击鼠标颜色恢复原状
Rectangle {
id: rectBtn; width: 100; height: 100
color: "#444444"
Text {anchors.centerIn: parent;text: qsTr("Click");color: "white";}
MouseArea {
id: mouseArea;anchors.fill: parent
onClicked: parent.color == "#444444" ? parent.color = "#ff8419" : parent.color = "#444444"
}
}