QML鼠标事件实现变色矩形

时间:2021-05-10 22:10:58

QML支持鼠标事件处理,我们可以利用这个来实现一个变色矩形示例,代码如下:

 import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2 Rectangle{
id: root
width: 512
height: 512
color: "gray" MouseArea {
anchors.fill: parent
acceptedButtons: Qt.LeftButton | Qt.RightButton onClicked: {
if (mouse.button == Qt.LeftButton){
color = Qt.rgba((mouse.x % 255)/255.0, (mouse.y % 255)/255.0, 0.6, 1.0);
}else if (mouse.button == Qt.RightButton){
Qt.quit();
}
} onDoubleClicked: {
color = "gray"
}
}
}