Update: Isn't it often the way: you ask a question and then discover the answer on your own a short time later.
It seems I have some confusion between referencing mouseX and mouseY in a MouseArea and getting the mouse data from the MouseEvent
If I change my code below to:
var pt = Qt.point( mouse.x, mouse.y)
from what I had:
var pt = Qt.point(mouseX, mouseY)
Then the newly created sprites are located at the click point. That's great but I am still not understanding the difference, particularly in this case since the MouseArea fills the entire window (parent).
The mouse data is the same in either approach, unless the mouse event has been propagated – then the mouse approach gives the correct data while mouseX, mouseY does not. That is the part that is confusing me.
Can anyone explain the difference in what is going on here?
I have made a reusable QML component which can load .png images with an alpha channel and handle clicks on transparent pixels by propagating the mouse event. I've got it working in the code below (any suggestions for improvement much welcomed) but it seems the mouse data is wrong.
In the image below I have marked the order and location of 3 clicks. In the log statements even though the mouse click position has changed, the reported position stays the same. So what is occurring is that although 3 sprites have been created, they are stacking on top of each other
Am I missing something about how a MouseArea reports the mouse position or how propagateComposedEvents works?
main clicked. Creating sprite at: 598.01953125 492.953125
graphic alpha clicked: 5.69921875 103.41015625 <----- EVENT PASSED THROUGH
main clicked. Creating sprite at: 598.01953125 492.953125
graphic alpha clicked: 121.953125 103.01953125 <----- EVENT PASSED THROUGH
graphic alpha clicked: 5.69921875 103.41015625 <----- EVENT PASSED THROUGH
main clicked. Creating sprite at: 598.01953125 492.953125
// main.qml
import QtQuick 2.5
import QtQuick.Controls 1.4
import QtQuick.Dialogs 1.2
ApplicationWindow {
id: appWindow
visible: true
width: 1024
height: 768
title: qsTr("QtQuick")
Item {
id: container
anchors.fill: parent
property var events: new Array()
property int counter: 0;
MouseArea {
anchors.fill: parent
onClicked: {
console.log("---------main clicked. Creating sprite at:", mouseX, mouseY);
var pt = Qt.point(mouseX, mouseY)
var component = Qt.createComponent("graphicAsset.qml");
var imageName = "Earth-icon.png";
var sprite = component.createObject(container, {"x": pt.x, "y": pt.y, "imageSource": imageName});
}
}
}
}
//graphicAsset.qml
import QtQuick 2.5
Canvas {
id: graphicAsset
width: 50
height: 50
property string imageSource;
onImageSourceChanged:loadImage(imageSource)
onImageLoaded: {
var ctx = getContext("2d")
var imageData = ctx.createImageData(imageSource)
graphicAsset.width = imageData.width;
graphicAsset.height = imageData.height;
x = x - (imageData.width /2);
y = y - (imageData.height /2);
requestPaint();
}
onPaint: {
if (isImageLoaded(imageSource)){
var ctx = getContext("2d")
var imageData = ctx.createImageData(imageSource)
ctx.drawImage(imageData, 0, 0)
}
}
MouseArea {
anchors.fill: parent
drag.target: parent
propagateComposedEvents: true
onClicked: {
var ctx = parent.getContext("2d")
var imageData = ctx.getImageData(mouseX, mouseY, 1, 1)
if (imageData.data[3] == 0 ){
console.log("graphic alpha clicked:", mouseX, mouseY);
mouse.accepted = false;
} else {
mouse.accepted = true;
}
}
}
}
Mouse events' x and y positions are relative to the MouseArea that generated the event, as well as the coordinates of the mouse cursor within the same area (named mouseX and mouseY).
Related
I am unsure what the markdirty() function does in QML. The QT documentation of that function does not seem clear to me.
My interpretation of this is that it allows us to track changes to a small subset of the canvas, so that any changes to that part redraws everything only in that part, using paint()
Doing requestPaint() on the other hand would be far more inefficient because it would redraw the whole canvas.
Is this correct? Some simple example codes would be quite helpful in understanding the usecase of markDirty()
That's a widely used term in programming especially GUI. Using that you can mark part of the canvas as in need of updating. So if this part is visible the render engine will fire paint(rect region) as soon as possible. In the onPaint handler you should repaint only items inside this region. requestPaint() does almost the same but for all the visible region.
Check the output in the example below:
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 800
height: 800
title: qsTr("QML Test")
Canvas {
property var shapes: [20,20,220,20,20,220,220,220]
id: canvas
width: 400
height: 400
anchors.centerIn: parent
onPaint: {
console.log(region);
var ctx = getContext("2d");
ctx.beginPath();
ctx.fillStyle = Qt.rgba(Math.random(),Math.random(),Math.random(),1);
// draw 4 circles
for(var i = 0;i < canvas.shapes.length;i +=2) {
var x = canvas.shapes[i];
var y = canvas.shapes[i + 1];
var width = 160;
var height = 160;
// check the circle is inside the region
if(!( (x + width) < region.x || x > (region.x + region.width) || (y + height) < region.y || y > (region.y + region.height) ) ) {
ctx.ellipse(x, y, width, height);
}
}
ctx.fill();
}
}
Timer {
id: timer
property int step: 0
interval: 2000
repeat: true
running: true
onTriggered: {
switch(step++) {
case 0: canvas.markDirty(Qt.rect(0, 0, 200, 200)); break;
case 1: canvas.requestPaint(); break;
case 2: timer.stop(); break;
}
}
}
}
I have 2 QQuickItems like below which I can fetch on C++ side using the QMLEngine like this.
QQuickItem * quick_item_1 = m_qml_engine->rootObjects()[0]->findChild<QQuickItem*>("quickitem1");
QQuickItem * quick_item_2 = m_qml_engine->rootObjects()[0]->findChild<QQuickItem*>("quickitem2");
Note: quick_item_1's immediate parent is different & quick_item_2's immediate parent is also different. But they both are drawn on the same application window into different immediate parents.
I am drawing both of them offscreen on a different QQuickItem. Let's call it new_parent_surface. I draw both these items on new_parent_surface by changing their parent to new_parent_surface like this.
quick_item_1->setParentItem(new_parent_surface);
quick_item_2->setParentItem(new_parent_surface);
This works fine for the objective of drawing them on a new parent QQuickItem. I get the both quick_item_1 & quick_item_2 drawn on new_parent_surface. Even though new_parent_surface is not drawn on UI, but if I take a snapshot using grabToImage of new_parent_surface, I can see the 2 items drawn on them. Fine till here.
However the positioning of quick_item_1 & quick_item_2 is not correct. I want to position them similar to the way they were positioned their original parent item. I can do some percentage math & try positioning them the same way as they were drawn on their original parent but isn't there a QQQuickItem or Qt API to translate this positioning to a new parent?
I tried to look into QQuickItem's mapping APIs like mapToItem & trying them out like this.
quick_item_2->mapToItem(new_parent_surface, quick_item_2->position());
But the positioning is still not correct.
So, how can I map a QQuickItem's position into its new parent QQuickItem after doing a setParentItem?
Items position is always relative to its parent. And position of the parent is relative to its parent and and so on. But you always can get both relative or global position. QML has lots of coordination translation function. Here is small example that could explain the issue:
import QtQuick 2.7
import QtQuick.Window 2.0
import QtQuick.Controls 2.1
Window {
id:container
width: 800
height: 800
visible: true
Component {
id: rect
Rectangle {
property bool imParent: false
x: 50 + Math.round(Math.random() * 550)
y: 50 + Math.round(Math.random() * 550)
width: 100 + Math.round(Math.random() * 100)
height: 100 + Math.round(Math.random() * 100)
color: Qt.rgba(Math.random(),Math.random(),Math.random(),1);
Drag.active: dragArea.drag.active
MouseArea {
id: dragArea
anchors.fill: parent
drag.target: parent
}
Text {
anchors.centerIn: parent
text: imParent ? "I'm parent" : "Drag me"
color: "white"
}
}
}
Rectangle {
id: blk
x: 10
y: 10
z: 100
parent: null
height: 50
width: 50
radius: 5
border.color: "white"
color: "black"
}
Repeater {
id: reptr
model: 5
property int pos: 0
Loader {
id: loader
sourceComponent: rect
onLoaded: {
if(blk.parent == null) {
blk.parent = loader.item;
loader.item.imParent = true;
}
}
}
}
Row {
anchors.horizontalCenter: container.contentItem.horizontalCenter
spacing: 2
Button {
text: "Reparent relative to parent"
onClicked: {
reptr.pos ++;
if(reptr.pos >= reptr.model) {
reptr.pos = 0;
}
var item = reptr.itemAt(reptr.pos).item;
blk.parent.imParent = false;
blk.parent = item;
blk.parent.imParent = true;
}
}
Button {
text: "Reparent relative to scene"
onClicked: {
reptr.pos ++;
if(reptr.pos >= reptr.model) {
reptr.pos = 0;
}
var item = reptr.itemAt(reptr.pos).item;
var coord = blk.mapToGlobal(blk.x, blk.y);
blk.parent.imParent = false;
blk.parent = item;
blk.parent.imParent = true;
coord = blk.mapFromGlobal(coord.x, coord.y);
blk.x = coord.x;
blk.y = coord.y;
}
}
}
}
In MouseArea.onEntered, can I detect if the cause for the event firing is only that the MouseArea moved and came to be under the cursor, rather than the other way round?
I thought of doing something like this: (pseudocode)
MouseArea {
// ...
property bool positionDirty = false
Connections {
target: window
onAfterRendering: {
positionDirty = false;
}
}
onMouseAreaPosChanged: {
positionDirty = true;
}
onEntered: {
if(positionDirty) {
positionDirty = false;
return;
}
// handle event here
}
}
But this makes the assumption that entered will be fired after mouseAreaPosChanged, and before window.afterRendering. And I'm not confident in that assumption.
Also, it doesn't work when an ancestor of the MouseArea moves, or when the MouseArea is positioned/sized via anchoring.
Assumptions:
This only affects the edge case, that both, the cursor and the MouseArea are moving.
My Assumption here is, that the movement of the cursor is handled before the movement of the MouseArea. I don't have any definite proof for this. Only my test with the solution below, suggests that.
Solution
The first challenge is to detect movement of the MouseArea. It might be that it moves, without its own x and y-values changing, e.g. if its parent is moving.
To solve this, I'll introduce two properties globalX and globalX. Then I use the trick from this answer on how to track a gobal position of an object.
Now I'll have two signals to handle: globalXChanged and globalYChanged.
According to my assumption, they are fired, after the mouseXChanged and mouseYChanged. I will use a flag isEntered to make sure, I only handle one of them, by setting it to true, if the first of them is fired.
I will use the cursor position on a globalMouseArea to determine, whether the cursor is within bounds of the MouseArea. This requires, the cursor is not in some other MouseArea at that time, or at least I know of it
-> With this I already succeeded in detecting the entrance.
The second challenge is to detect the exit. Here we have 4 cases to distinguish:
Cursor enters and leaves the MouseArea because of it's movement.
Cursor enters and leaves the MouseArea because of the movement of the MouseArea
Cursor enters because the MouseArea moves, and leaves, because the cursor moves
Cursor enters because it moves, and leaves as the MouseArea moves away.
The first would be easy to handle. After it enters we handle entered and when it leaves we handle exited. But after the fix, mentioned by Mitch we can't rely on this anymore.
So we will not set hoverEnabled: true and map the position of the cursor to the targetMouseArea whenever either the cursor moves, or the targetMouseArea moves, and act accordingly.
import QtQuick 2.7
import QtQuick.Controls 2.0
ApplicationWindow {
id: root
visible: true
width: 400; height: 450
MouseArea {
id: globalMouseArea
anchors.fill: parent
hoverEnabled: true
onClicked: ani.restart()
}
Rectangle {
x: 300
y: 300
width: 50
height: 50
color: 'green'
}
Rectangle {
id: rect
width: 50
height: 50
color: 'red'
Text {
text: targetMouseArea.isEntered.toString()
}
MouseArea {
id: targetMouseArea
anchors.fill: parent
signal enteredBySelfMovement
signal enteredByMouseMovement
onEnteredByMouseMovement: console.log('Cause: Mouse')
onEnteredBySelfMovement: console.log('Cause: Self')
property point globalPos: {
var c = Qt.point(0, 0)
var itm = this
for (; itm.parent !== null; itm = itm.parent) {
c.x += itm.x
c.y += itm.y
}
return c
}
property bool isEntered: false
function checkCollision(sig) {
if ((globalPos.y < globalMouseArea.mouseY)
&& (globalPos.y + height > globalMouseArea.mouseY)
&& (globalPos.x < globalMouseArea.mouseX)
&& (globalPos.x + width > globalMouseArea.mouseX)) {
if (!isEntered) {
isEntered = true
sig()
}
}
else if (isEntered && !containsMouse) {
console.log(isEntered = false)
}
}
onGlobalPosChanged: {
checkCollision(enteredBySelfMovement)
}
Connections {
target: globalMouseArea
onPositionChanged: {
targetMouseArea.checkCollision(targetMouseArea.enteredByMouseMovement)
}
}
}
}
NumberAnimation {
id: ani
target: rect
properties: 'x,y'
from: 0
to: 300
running: true
duration: 10000
}
}
Problems left: When we clicked within the targetMouseArea, as long as a button is pressed, we won't detect the leaving.
You can check whether mouseX, mouseY were changed since last event.
property int previousMouseX = mouseX; // or use other values to init
property int previousMouseY = mouseY; // e.g., 0, x, parent.x,
// or set it from extern
onEntered() {
if (mouseX != previousMouseX || mouseY != previousMouseY) {
// TODO do something
previousMouseX = mouseX;
previousMouseY = mouseY;
}
}
In case mouseX, mouseY are relative to the mouse area 0,0 you can use mapFromItem(null, 0, 0) to get the absolute values.
I want to make an area, where a small rectangles appear in the places it where clicked. Later on I would try to add an ability to move those rectangles by dragging.
After studying Help, I tried to accomplish this with a MouseArea and a Component containing a Rectangle. Then, with onClicked, I was trying to create a new copy of a Component, but I failed whatever I tried (createComponent, createObject, etc.).
What is the correct way of creating a copy of an object in this case?
Am I using right tools for this goal?
MouseArea {
Component {
id: rect
Rectangle {
width: 10
height: 10
}
}
onClicked: < what? >
}
you can create a QML object from a string of QML using the Qt.createQmlObject() and set it's x and y values to mouseX and mouseY :
import QtQuick 2.3
import QtQuick.Window 2.0
Window {
id : root
visible: true
width: 1000
height: 500
MouseArea {
anchors.fill: parent
onClicked:{
var newObject = Qt.createQmlObject('import QtQuick 2.3; Rectangle {color: "red"; width: 10; height: 10}',
root);
newObject.x = mouseX;
newObject.y = mouseY;
}
}
}
Also if you put the code for your rectangle in a separate qml file say myRect.qml, you can create the object from the qml file by :
onClicked:{
var component = Qt.createComponent("myRect.qml");
var newObject = component.createObject(root, {"x": mouseX, "y": mouseY});
}
My problem is the following: I have a custom QML object based on a Rectangle, and I need to execute some javascript function with the width & height of this object when it's created.
To do that, I use Component.onCompleted to execute the javascript but in this function the width and height properties are wrong (like 0;0 or 0;-30), as if they were not yet created.
Code:
import QtQuick 2.3
import "js/kloggr.js" as Game
Rectangle {
property var kloggr: undefined
MouseArea {
anchors.fill: parent
// outputs the right values (about 400;600)
onClicked: console.log(width+";"+height);
}
Component.onCompleted: {
Game.kloggr = this;
kloggr = new Game.Kloggr(width, height);
console.log(width+";"+height); // outputs 0;-30
}
}
This object is created like this:
Kloggr {
id: kloggr
anchors.top: parent.top
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: pauseBtn.top
}
(I've removed the irrelevant parts of the code)
So what did I do wrong, or what could I do to get the same result?
You have forget to set the width and height of your Rectangle ...
import QtQuick 2.3
import "js/kloggr.js" as Game
Rectangle {
width: 300
height: 300
property var kloggr: undefined
MouseArea {
anchors.fill: parent
// outputs the right values (about 400;600)
onClicked: console.log(width+";"+height);
}
Component.onCompleted: {
Game.kloggr = this;
kloggr = new Game.Kloggr(width, height);
console.log(width+";"+height); // outputs 0;-30
//now h + w = 300
}
}
If your use anchors, change your Rectangle by Item, for exemple
import QtQuick 2.3
import "js/kloggr.js" as Game
Item{
//without W and Height if you don't use the designer, if you use the designer you should set a default size
property var kloggr: undefined
Rectangle{
anchors.fill : parent
MouseArea {
anchors.fill: parent
// outputs the right values (about 400;600)
onClicked: console.log(width+";"+height);
}
Component.onCompleted: {
Game.kloggr = this;
kloggr = new Game.Kloggr(width, height);
console.log(width+";"+height); // outputs 0;-30
}
}//end of rectangle
} //end of item
I did not find out it if was a bug or something but I found a workaround: instead of using Component.onCompleted I used onVisibleChanged:
onVisibleChanged: {
if (visible && kloggr === undefined) {
Game.kloggr = this;
kloggr = new Game.Kloggr(width, height);
}
}
It seems that the width and height properties are only valid when the object is set to visible...
Thank you #yekmen for your help