Get MouseEvents while MousePressed - qt

I have several QML Items that all have Mouse Areas.
What I want to achieve is:
Click one of the items and start tracking the mouse
Add every other Item that the mouse enters into a list
End the tracking once the mouse is released
Sample Code:
import QtQuick 2.3
import QtQuick.Window 2.2
Window {
visible: true
width:500; height: 200;
Rectangle{
anchors.left: parent.left
color: 'red'
width: 200; height: 200;
MouseArea {
anchors.fill: parent
hoverEnabled: true
onReleased: console.log('onReleased red')
onEntered: console.log('onEntered red')
onPressed: {
console.log('onPressed red')
mouse.accepted = false
}
}
}
Rectangle{
anchors.right: parent.right
color: 'blue'
width: 200; height: 200;
MouseArea {
anchors.fill: parent
hoverEnabled: true
onReleased: console.log('onReleased blue')
onEntered: console.log('onEntered blue')
onPressed: console.log('onPressed blue')
}
}
}
Expected behaviour:
Click one Rectangle
Get on entered event if I enter the other element
Get the Released event
The sample code has both Version I tried, with and without accepting the mousePressed event.
What happens is:
If I press the mouse over one rectangle I do not get the onEnter event for all my other rectangles.
If I do not accept the onPressed event, I get the onEnter Events but not the onReleased event.
Note:
I already found this Answer which uses a DropArea as workaround which is not what I want to use if there is any other solution.
Even though the Example may look like Drag&Drop it is not what I want.
Please see the "What I want to achieve" at the top of this Question.

You will not be able to achieve what you want just using standart MouseArea components. Standart QML components are kinda limited in their functionality.
What you have to do is to create your own MouseArea component through QML extension.
In our project we also encountered lots of problems with mouse handling, so how we managed to do it was:
Subclassed QQuickItem, and inside of this class we just tracked the mouse movement, and mouse buttons states. One important thing wass to install EventFilters defined by this class.
In QML, created a Simple Component that Checks if mouse is inside of currrent component.
If you need, i could post also a code here so you have an idea.
The implementation is not the prettiest, but it works

Related

How can I disable the mouse wheel for a TextArea without disabling the entire control?

I'm using a TextArea to display multi-line text with embedded <IMG ...> tags in the delegate for a ListView. I have it set to read-only (and not disabled) because I need hyperlinks in the text to be clickable so I need to make use of its onLinkActivated event handler. This is normally something that would call for a Label (which does not handle mouse wheel events), but a Label does not render line-breaks correctly when the text includes <IMG ...> tags in the HTML.
The problem I'm having is that a TextArea handles mouse wheel events even when it is read-only, so if the cursor happens to be over one of the visible TextArea controls, the ListView will not respond to mouse wheel events (and so it does not scroll). In other words, the TextArea is capturing the mouse wheel events and I want it to not do this.
I see in the docs that controls have a wheelEnabled: property, but TextArea does not seem to support this.
Update: here is a minimum code sample that demonstrates the problem:
import QtQuick.Controls 1.4 as Controls
Rectangle {
id: test
color: "white"
width: 300
anchors {
left: parent.left
top: parent.top
bottom: parent.bottom
}
Controls.ScrollView {
id: _scrollview
anchors.fill: parent
ListView {
anchors.fill: parent
model: 100
delegate: Rectangle {
id: tableRow
width: test.width
height: 50
color: "yellow"
TextArea {
width: test.width / 2
height: tableRow.height
readOnly: true
text: "Row # " + index
}
}
}
}
}
If you hold the mouse cursor over the right side of this listview (i.e. not over the TextArea control in the row), the mouse wheel works as expected. But if you hold the mouse cursor over the TextArea in any of the rows, the ListView will not scroll with the mouse wheel (because the readOnly TextView is capturing the events).
This is actually pretty easy, too bad I wasted the bounty. All this requires is a MouseArea positioned over the TextArea like so:
MouseArea {
anchors.fill: txtTester
onPressed: {
mouse.accepted = false
}
onReleased: {
mouse.accepted = false
}
property int scrollValue: 15
onWheel: {
if (wheel.angleDelta.y < 0) {
//make sure not to scroll too far
if (!_scrollview.flickableItem.atYEnd)
_scrollview.flickableItem.contentY += scrollValue
}
else {
//make sure not to scroll too far
if (!_scrollview.flickableItem.atYBeginning)
_scrollview.flickableItem.contentY -= scrollValue
}
}
}
This ignores press and release events so clicking on hyperlinks in the TextArea still works, but it intercepts mouse wheel events and applies them to moving the ScrollView as if the TextArea were not there.
Try this out:
import QtQuick 2.4
import QtQuick.Window 2.2
import QtQuick.Controls 1.3
Window {
visible: true
width: 400
height: 200
TextArea {
id: text
anchors.fill: parent
text: "Current\ntext\n\\to\nmove\ndown\ndown\ndown
\ndown\ndown\ndown\ndown\ndown\ndown\ndown"
flickableItem.interactive: false
}
}
TextArea has flickableItem.enabled property. Since you're stuck with !t 5.6 this should work for you.
EDIT: changed to flickableItem.interactive instead.

QML - How to drag a ToolButton?

The QT documentation has this tutorial.
I initially followed it exactly, and it works. I then made two modifications:
I replaced the ListView with a GridView (that works without #2).
I attempted to add a ToolButton to my delegate inside the Rectangle "content" like so:
Rectangle {
id: content
ToolButton {
id: toolButton
icon.color = "transparent"
icon.source = "image://Loader/iconName"
}
Drag.active: dragArea.held
Drag.source: dragArea
Drag.hotSpot.x: width / 2
Drag.hotSpot.y: height / 2
}
This does not work, the ToolButton appears to be processing the mouse movements and not propagating the messages (I can click the button, but I can not drag it)? This is actually somewhat expected to be honest.
So that said, does anyone have a good way of dragging ToolButtons around? Or is it just accepted that you can't do that? I have tried various combinations of Rectangles and MouseAreas but I can't seem to do one without breaking the other (ie either the drag fails or the button fails).
You can move the MouseArea as a child of the ToolButton to manage the drag with pressAndHold, and propagate the click to keep the button behavior:
Rectangle {
id: content
ToolButton {
id: toolButton
// bind the visual state of the button to the MouseArea
background: Rectangle {
color: marea.pressed
? Qt.darker("blue")
: marea.containsMouse
? Qt.lighter("blue")
: "blue" // use your desired colors
}
MouseArea {
id: marea
property bool held: false
drag.target: held ? content : undefined
drag.axis: Drag.YAxis
anchors.fill: parent
hoverEnabled: true
onPressAndHold: held = true
onReleased: held = false
onClicked: toolButton.clicked() // propagate clicked event to the ToolButton
}
}
// ...
}

QML: referencing root window by parent reference is unreliable

Qt/QML question. Using Qt 5.7.
Take the following simple QML program that displays a red rectangle and a blue rectangle aligned vertically. Click handlers for both rectangles attempt to change the color of the parent host window. But with a subtle difference. The red rectangle references the host window directly by it's id (rootWindow). The blue click handler changes color via a parent reference.
The former case works fine. The latter case does not work. It seems like the root window is treated specially and isn't directly part of the parent/child hierarchy, even if the Rectangles are logically nested in the code that way.
Can someone explain the rule around this?
import QtQuick 2.7
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
id: rootWindow
color: "#ffffee"
Rectangle {
id: rect1; width: 50; height: 50; color:"red"
MouseArea {
anchors.fill: parent;
onClicked: {
print("rect1 clicked");
rootWindow.color = "green"; // works fine
}
}
}
Rectangle {
id: rect2; width: 50; height: 50; color:"blue"
anchors.top: rect1.bottom
MouseArea {
anchors.fill: parent;
onClicked: {
print("rect2 clicked");
rect2.parent.color = "pink"; // does not work
}
}
}
}
If you add the following line to the onClicked handler, you'll see that its parent isn't the Window:
print(rect2.parent)
Output:
qml: QQuickRootItem(0x18b18147bc0)
This is explained not-so-visibly in the documentation for Window:
If you assign an Item to the data list, it becomes a child of the Window's contentItem, so that it appears inside the window. The item's parent will be the window's contentItem, which is the root of the Item ownership tree within that Window.
The window itself isn't an item, so it uses contentItem instead so that child items can have a parent.
However, in Qt 5.7, Window got an attached property that can be used to access the window of an item:
rect2.Window.window.color = "pink";
Whichever item comes before the Window.window part will be the item that the attached property is used on. You could use it on any item in this scene (e.g. the MouseArea), as they all belong to the same window.
Note that attached properties create a QObject-derived object for each unique item they're used on, so be mindful of how you use them, especially in items that are created in very large numbers.

Gridview and MouseArea inside conflict

I have code like this:
import QtQuick 2.0
import QtQuick.Window 2.0
Window {
visible: true
width: 500
height: 500
GridView {
id: grid
anchors.fill: parent
cellWidth: 30
cellHeight: 30
model: 120
delegate: Rectangle {
width: grid.cellWidth
height: grid.cellHeight
color: "grey"
}
MouseArea {
anchors.fill: parent
onPressed: console.info(">> PRESSED triggered")
onMouseXChanged: console.info(">> " + mouseX)
onReleased: console.info(">> RELEASED triggered")
preventStealing: true
propagateComposedEvents: true
}
}
}
When I hold mouse button down and move it strictly along X axis, all the signals in MouseArea trigger. But when the mouse is also moved up or down, along Y axis, the onMouseXChanged and onReleased signals do not trigger. It seems that GridView intercepts MouseArea's signals, stealing them from the MouseArea. How can I make them work together: GridView with MouseArea inside?
Set preventStealing to true in your MouseArea.
This property holds whether the mouse events may be stolen from this MouseArea.
If a MouseArea is placed within an item that filters child mouse events, such as Flickable, the mouse events may be stolen from the MouseArea if a gesture is recognized by the parent item, e.g. a flick gesture. If preventStealing is set to true, no item will steal the mouse events.

New drag-and-drop mechanism does not work as expected in Qt-Quick (Qt 5.3)

I've tried to implement drag and drop in Qt 5.3 using the new QML types Drag, DragEvent and DropArea. This is the original example from the documentation of the QML Drag type with some small modifications:
import QtQuick 2.2
Item {
width: 800; height: 600
DropArea {
width: 100; height: 100; anchors.centerIn: parent
Rectangle {
anchors.fill: parent
color: parent.containsDrag ? "red" : "green"
}
onEntered: print("entered");
onExited: print("exited");
onDropped: print("dropped");
}
Rectangle {
x: 15; y: 15; width: 30; height: 30; color: "blue"
Drag.active: dragArea.drag.active
// Drag.dragType: Drag.Automatic
Drag.onDragStarted: print("drag started");
Drag.onDragFinished: print("drag finished");
MouseArea {
id: dragArea
anchors.fill: parent
drag.target: parent
}
}
}
Expected behaviour: The small blue rectangle (drag target) can be dragged around with the mouse. If dragged over the larger green rectangle in the center of the window, this rectangle turns red and back to green when leaving. In addition, the signals dragStarted, entered, exited, dropped and dragFinished are emitted in time and the corresponding signal handlers print out their messages.
Experienced behaviour:
Depends on Drag.dragType (see commented line above):
Drag.dragType is NOT set (default is Drag.Internal):
Drag and drop works as described, but only the signals entered and exited are emitted. The other signals (dragStarted, dragFinished and dropped) are suppressed. So there is no way to react to the drop in the DropArea.
Drag.dragType is set to Drag.Automatic:
All of the signals are emitted now, but the blue rectangle (drag target) does not move with the mouse. Instead, the mouse cursor changes its shape to visualize possible drop targets. After the mouse has been released, the blue rectangle jumps to the latest mouse position.
Neither of these two variants are pleasing. How can I get all signals and still be able to drag around the drag target? Unfortunately the documentation is everything but clear about drag-and-drop in QML, especially about the ominous Drag.dragType.
If you open the QQuickDrag source code and look at the differences between start(), which is used by Drag.Internal, and startDrag() which is used by Drag.Automatic, the difference is pretty obvious. start() sets up an event change listener, which it then uses to update the position of the attached object. startDrag() doesn't do this.
Why does it work this way? I have no idea! The QtQuick 2 drag and drop documentation certainly has room for improvement here.
There is a fairly simple workaround: take the best from both worlds. Use Drag.Automatic, but instead of setting Drag.active, call start() and drop() manually. It won't invoke Drag.onDragStarted() and Drag.onDragFinished() but you essentially get those for free anyway by listening for a change in the MouseArea's drag.active.
Here's the concept in action:
import QtQuick 2.0
Item {
width: 800; height: 600
DropArea {
width: 100; height: 100; anchors.centerIn: parent
Rectangle {
anchors.fill: parent
color: parent.containsDrag ? "red" : "green"
}
onEntered: print("entered");
onExited: print("exited");
onDropped: print("dropped");
}
Rectangle {
x: 15; y: 15; width: 30; height: 30; color: "blue"
// I've added this property for simplicity's sake.
property bool dragActive: dragArea.drag.active
// This can be used to get event info for drag starts and
// stops instead of onDragStarted/onDragFinished, since
// those will neer be called if we don't use Drag.active
onDragActiveChanged: {
if (dragActive) {
print("drag started")
Drag.start();
} else {
print("drag finished")
Drag.drop();
}
}
Drag.dragType: Drag.Automatic
// These are now handled above.
//Drag.onDragStarted: print("drag started");
//Drag.onDragFinished: print("drag finished");
MouseArea {
id: dragArea
anchors.fill: parent
drag.target: parent
}
}
}
I realize it's not a completely satisfying solution, but it does match your expected behavior.
This solution offers:
Notifications for all of the desired events: drag started, drag finished, enter drag area, exit drag area, and dropped in drag area.
The drag animation is automatically handled by QtQuick. The square doesn't freeze in place like it does when running the sample code with Drag.Automatic.
What it doesn't offer:
An explanation as to why QtQuick's drag and drop functionality works this way, or whether it's even the intended behavior by the developers. The current documentation seems ambiguous.
Just ran into this myself (using Qt 5.2, but the same problem exists there). I've got a 'slider box' on the X-axis and just wanted to know when the drag was finished... instead of responding to every position change along the way. My workaround involved hacking the states/transitions, with a ScriptAction to provide the logic. This is the simplified version for mimicking a response to the "onDragFinished" signal. So while it doesn't cover all your drag/drop signals, it might get you pointed in the right direction.
Rectangle {
id: sliderControl
height: coordinates.height
width: 80
color: "#F78181"
border.color: "#FE2E2E"
border.width: 1
opacity: 0.4
MouseArea {
id: mouseArea
anchors.fill: parent
drag.target: sliderControl
drag.axis: Drag.XAxis
drag.minimumX: 0
drag.maximumX: view.width - sliderControl.width
hoverEnabled: true
}
states: [
State {
name: "dragging"
when: mouseArea.drag.active
},
State {
name: "finished_dragging"
when: !mouseArea.drag.active
}
]
transitions: [
Transition {
from: "dragging"
to: "finished_dragging"
ScriptAction {
script: console.log("finished dragging script");
}
}
]
}
ps - I know that such a 'workaround' doesn't qualify for the bounty parameters, but I was pretty bummed to find only your question (no solutions) when I searched for help on the issue. Hopefully anyone else stumbling down this path will find this useful. Unfortunately, I've got no clue what's going on with QML's Drag.dragType either.

Resources