QML支持鼠标事件处理,我们可以利用这个来实现一个变色矩形示例,代码如下:
1 import QtQuick 2.4 2 import QtQuick.Controls 1.3 3 import QtQuick.Window 2.2 4 import QtQuick.Dialogs 1.2 5 6 Rectangle{ 7 id: root 8 512 9 height: 512 10 color: "gray" 11 12 MouseArea { 13 anchors.fill: parent 14 acceptedButtons: Qt.LeftButton | Qt.RightButton 15 16 onClicked: { 17 if (mouse.button == Qt.LeftButton){ 18 color = Qt.rgba((mouse.x % 255)/255.0, (mouse.y % 255)/255.0, 0.6, 1.0); 19 }else if (mouse.button == Qt.RightButton){ 20 Qt.quit(); 21 } 22 } 23 24 onDoubleClicked: { 25 color = "gray" 26 } 27 } 28 }