Last active
July 4, 2022 08:35
-
-
Save vannell/c9c452e43eadf4f2e087 to your computer and use it in GitHub Desktop.
QML Rectangle intersection calculation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import QtQuick 2.4 | |
Item { | |
id: root | |
width: 800 | |
height: 600 | |
property int xOverlap: 0 | |
property int yOverlap: 0 | |
Rectangle { | |
id: rect1 | |
width: 200 | |
height: 100 | |
color: "red" | |
opacity: 0.5 | |
MouseArea { | |
anchors.fill: parent | |
drag.target: parent | |
drag.axis: Drag.XAndYAxis | |
} | |
onXChanged: computeOverlap() | |
onYChanged: computeOverlap() | |
} | |
Rectangle { | |
id: rect2 | |
width: 200 | |
height: 100 | |
color: "blue" | |
opacity: 0.5 | |
MouseArea { | |
anchors.fill: parent | |
drag.target: parent | |
drag.axis: Drag.XAndYAxis | |
} | |
onXChanged: computeOverlap() | |
onYChanged: computeOverlap() | |
} | |
Column { | |
anchors.right: parent.right | |
anchors.top: parent.top | |
spacing: 10 | |
Text { | |
text: "xOverlap: " + xOverlap | |
} | |
Text { | |
text: "yOverlap: " + yOverlap | |
} | |
} | |
Component.onCompleted: rect2.x = rect1.width + 10 | |
function computeOverlap() { | |
var r1 = rect1.mapToItem(null, 0, 0, rect1.width, rect1.height) | |
var r2 = rect2.mapToItem(null, 0, 0, rect2.width, rect2.height) | |
xOverlap = Math.min(r1.x + r1.width, r2.x + r2.width) - Math.max(r1.x, r2.x); | |
yOverlap = Math.min(r1.y + r1.height, r2.y + r2.height) - Math.max(r1.y, r2.y); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment