Better way to reparent visual items in QML - qt

It would seem that in the design of QML user reparent was not really "envisioned", because even though it is possible, it involves creating and changing states, which is just not convenient to add to each and every item.
import QtQuick 1.0
Item {
width: 200; height: 100
Rectangle {
id: redRect
width: 100; height: 100
color: "red"
}
Rectangle {
id: blueRect
x: redRect.width
width: 50; height: 50
color: "blue"
states: State {
name: "reparented"
ParentChange { target: blueRect; parent: redRect; x: 10; y: 10 }
}
MouseArea { anchors.fill: parent; onClicked: blueRect.state = "reparented" }
}
}
I was wondering if there is a more elegant way to reparent items without polluting items with unnecessary states?

not certain if you need to use QtQuick 1.0, but with 2.0 this also works and is imo more straight forward.
import QtQuick 2.0
Item {
width: 200; height: 100
Rectangle {
id: redRect
width: 100; height: 100
color: "red"
}
Rectangle {
id: blueRect
x: redRect.width
width: 50; height: 50
color: "blue"
MouseArea { anchors.fill: parent; onClicked:
{ blueRect.parent = redRect; blueRect.x = 10; blueRect.y = 10 }
}
}
}

Related

Qt : How to grab a snapshot of a QQuickItem leaving out its child QQuickItems from the grabbed result

My question is a follow up on this discussion.
Yes. Following way of grabToImage can get me a snapshot of any particular QQuickItem like parent_rect below.
Rectangle {
id: parent_rect
width: 400
height: 400
Rectangle {
id: child_rect1
width: parent.width/4
height: parent.height/4
}
Rectangle {
id: child_rect2
width: parent.width/4
height: parent.height/4
}
}
// ...
parent_rect.grabToImage(function(result) {
result.saveToFile("something.png");
});
Problem:
But this grabToImage gets me the snapshot of the all its children as well namely child_rect1 and child_rect2.
Question:
How can I get the snapshot of parent_rect only without getting its children add into the returned result?
One possible solution is to hide the children and then restore visibility.
Example:
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
function grabWithoutChildren(item, filename){
var isVisibleList = []
var i
for(i in item.children){
isVisibleList[i] = item.children[i].visible
item.children[i].visible = false
}
item.grabToImage(function(result) {
result.saveToFile(filename)
for(i in item.children){
item.children[i].visible = isVisibleList[i]
}
})
}
Rectangle {
id: parent_rect
width: 400
height: 400
color: "red"
Rectangle {
id: child_rect1
width: parent.width/4
height: parent.height/4
color: "blue"
}
Rectangle {
id: child_rect2
x: 10
y: 10
width: parent.width/4
height: parent.height/4
color: "green"
Rectangle{
x:50
y:50
width: 100
height: 100
color: "white"
}
}
}
Component.onCompleted: grabWithoutChildren(parent_rect, "something.png")
}

QML 'Custom Menu' option moving upwards

I am trying to create a "menu" in QML with custom data in each option
For requirements of my application, I need to show it loading the QML file dynamically (Qt.createComponent). What I need is to show some fixed options in the bottom part, and when clicked the top one, another options appear below this top option, which keeps in the top
A simple example. I have this menu:
Option 4
Option 2
Option 1
And when clicked in Option 4, the menu changes to
Option 4
Option 3
Option 2
Option 1
So Option 4 is moved upwards and Option 3 appears.
I would like to have a 'shadow' around all my menu (I added a DropShadow component for that purpose).
I have this simple test code, where I have a main Rectangle (to be surrounded by the shadow), and 2 Rectangles inside.
Rect1 for the fixed part (Option 1, Option 2), and Rect2 for the 'movable' part (Option 3, Option 4).
Rect2 is behind Rect1 (z: -1), and located to have only Option 4 visible, above Option 2. When clicked Option 4, Rect2 is moved upwards and all options are visible.
To achieve that, I have to update Rect2 visible height, and main window position (y value), since main window height depends on this Rect2 visible height.
I have it working, but it flicks a lot since 2 variables changes ('fixed panel' is moved upwards and back).
I have also tried with a ParallelAnimation for 2 values, but no success.
Any idea to have this menu with a smooth movement?
Main.qml:
import QtQuick 2.0
Rectangle
{
id: window
property variant win: undefined;
Component.onCompleted:
{
var component = Qt.createComponent("TestMenu.qml");
win = component.createObject(window, {"x": 500, "y": 500});
win.show();
}
}
TestMenu.qml:
import QtQuick 2.0
import QtQuick.Window 2.1
import QtGraphicalEffects 1.0
Window {
id: window
flags: Qt.Tool | Qt.FramelessWindowHint
height: panel.height
color: "transparent"
property int radiusShadow: 20
property int iOptionHeight: 30
Rectangle {
id: panel
anchors { centerIn: parent}
height: menu1.height + menu2.heightVisible + 2*radiusShadow
width: window.width - 2*radiusShadow
color: "transparent"
Rectangle {
id: menu1
anchors { bottom: parent.bottom; bottomMargin: radiusShadow }
width: parent.width
height: column1.children.length * iOptionHeight
Column {
id: column1
anchors.fill: parent
Rectangle {
color: "red";
Text { text: qsTr("option 2") }
height: iOptionHeight; width: parent.width
}
Rectangle {
color: "green";
Text { text: qsTr("option 1") }
height: iOptionHeight; width: parent.width
}
}
}
Rectangle {
id: menu2
property int heightVisible: iOptionHeight
anchors { top: parent.top; topMargin: radiusShadow; left: menu1.left }
width: parent.width
height: column2.children.length * iOptionHeight
z: -1
Column {
id: column2
anchors.fill: parent
Rectangle {
id: blue
property bool bOpen: false
color: "blue";
height: iOptionHeight; width: parent.width
Text { text: qsTr("option 4") }
MouseArea {
anchors.fill: parent
onClicked: {
blue.bOpen = !blue.bOpen;
panel.showHideMenu2(blue.bOpen);
}
}
}
Rectangle {
color: "pink";
Text { text: qsTr("option 3") }
height: iOptionHeight; width: parent.width
}
}
}
function showHideMenu2(bShow)
{
if (bShow)
{
window.y -= iOptionHeight
menu2.heightVisible += iOptionHeight;
}
else
{
window.y += iOptionHeight
menu2.heightVisible -= iOptionHeight;
}
}
}
DropShadow {
id: dropShadow
visible: true
anchors.fill: panel
radius: radiusShadow
samples: 24
color: "#40000000"
source: panel
}
}
As a quick answer for your question, you can get what you want using Behavior animation for a property change.
Here, Behavior animation will be used on y (position) change of your window, and for height change of respective rectangles.
Here is the patch for your code I recommend you to apply to see smooth movement:
## -10,6 +10,9 ##
property int radiusShadow: 20
property int iOptionHeight: 30
+ property int animationDuration: 500 // ms
+
+ Behavior on y { NumberAnimation { duration: window.animationDuration } }
Rectangle {
id: panel
## -18,6 +21,7 ##
height: menu1.height + menu2.heightVisible + 2*radiusShadow
width: window.width - 2*radiusShadow
color: "transparent"
+ Behavior on height { NumberAnimation { duration: window.animationDuration } }
Rectangle {
id: menu1
## -25,6 +29,7 ##
anchors { bottom: parent.bottom; bottomMargin: radiusShadow }
width: parent.width
height: column1.children.length * iOptionHeight
+ Behavior on height { NumberAnimation { duration: window.animationDuration } }
Column {
id: column1
## -52,6 +57,8 ##
width: parent.width
height: column2.children.length * iOptionHeight
+ Behavior on height { NumberAnimation { duration: window.animationDuration } }
+
z: -1
Column {
## -64,6 +71,7 ##
color: "blue";
height: iOptionHeight; width: parent.width
Text { text: qsTr("option 4") }
+ Behavior on height { NumberAnimation { duration: window.animationDuration } }
MouseArea {
anchors.fill: parent
## -77,6 +85,7 ##
color: "pink";
Text { text: qsTr("option 3") }
height: iOptionHeight; width: parent.width
+ Behavior on height { NumberAnimation { duration: window.animationDuration } }
}
}
}
## -105,4 +114,4 ##
color: "#40000000"
source: panel
}
-}+}
I have tried with a model and a ListView (code is simpler now), but I don't know where and how insert an 'Animation' or a 'Behaviour' to achieve my target, if it is possible to do it (I have tried several options with no success...)
The expected effect is that the 1st rectangle moves up when the 2nd appears, so the bottom one keeps in its position (at bottom). But the default behaviour when I add an element to the model is that the list increased the height downwards
Maybe anyone could help...
My code:
import QtQuick 2.0
import QtQuick.Controls 1.4
Rectangle {
id: rootItem
width: 400
height: list.height
ListModel {
id: modelRects
ListElement { rectColor: "green" }
ListElement { rectColor: "orange" }
}
ListView {
id: list
height: modelRects.count * 30
model: modelRects
delegate: Rectangle {
id: delegate
height: 30
width: rootItem.width
color: rectColor
MouseArea {
anchors.fill: parent
onClicked: onRectClicked(index);
}
}
}
function onRectClicked(index)
{
if (index == 0)
{
if (modelRects.count == 2)
modelRects.insert(1, {"idRect": 2, "rectColor": "red"});
else
modelRects.remove(1, 1);
}
}
}

QML ListView, How to make list elements to not overlap the header, when scrolling

I have ListView with a header delegate enabled. I have a header positioning property set to "OverlayHeader". The header will stay in place when scrolling through the elements. However, the elements will overlap the header. Is there a way to prevent this.
Example of list elements overlapping the header.
import QtQuick 2.5
Rectangle {
width: 360; height: 600
ListView {
width: 350; height: 200
anchors.centerIn: parent
id: myList
model: myModel
highlight: highlightBar
clip: true
snapMode: ListView.SnapToItem
headerPositioning: ListView.OverlayHeader
header: Rectangle {
id: headerItem
width: myList.width
height:50
color: "blue"
Text {
text: "HEADER"
color: "red"
}
}
delegate: Item {
id: delegateItem
width: 400; height: 20
clip: true
Text { text: name
}
MouseArea {
id: mArea
anchors.fill: parent
onClicked: { myList.currentIndex = index; }
}
}
}
Component {
id: highlightBar
Rectangle {
width: parent.width; height: 20
color: "#FFFF88"
}
}
ListModel {
id: myModel
}
/* Fill the model with default values on startup */
Component.onCompleted: {
for(var i = 0; i < 100; i++) {
myModel.append({ name: "Big Animal : " + i});
}
}
}
The header's default z value is 1, so you can set it to a higher value to ensure that it's over the delegates:
import QtQuick 2.5
Rectangle {
width: 360
height: 600
ListView {
width: 350
height: 200
anchors.centerIn: parent
id: myList
model: myModel
highlight: highlightBar
clip: true
snapMode: ListView.SnapToItem
headerPositioning: ListView.OverlayHeader
header: Rectangle {
id: headerItem
width: myList.width
height: 50
z: 2
color: "blue"
Text {
text: "HEADER"
color: "red"
}
}
delegate: Item {
id: delegateItem
width: 400
height: 20
Text {
text: name
}
MouseArea {
id: mArea
anchors.fill: parent
onClicked: {
myList.currentIndex = index
}
}
}
}
Component {
id: highlightBar
Rectangle {
width: parent.width
height: 20
color: "#FFFF88"
}
}
ListModel {
id: myModel
}
/* Fill the model with default values on startup */
Component.onCompleted: {
for (var i = 0; i < 100; i++) {
myModel.append({
name: "Big Animal : " + i
})
}
}
}
Note that clipping view delegates is bad for performance.

Animation of y position for a Column centerd in parent

I have a Column with three elements and one element can change its visibility if the user hits the spacebar. To make the visibility change look smoothly I can add a move transition:
ApplicationWindow {
title: qsTr("Hello World")
width: 640
height: 480
visible: true
Column {
spacing: 2
Rectangle { color: "red"; width: 50; height: 50 }
Rectangle { id: greenRect; color: "green"; width: 20; height: 50 }
Rectangle { color: "blue"; width: 50; height: 20 }
move: Transition {
NumberAnimation { properties: "x,y"; duration: 1000 }
}
focus: true
Keys.onSpacePressed: greenRect.visible = !greenRect.visible
}
}
This works. But if I center the Column in its parent the visibility change also results in a new height for the Columnand therefore also to a new y position.
Now I don't want the Column to 'jump' to its new position but also to move smoothly. So I added this to the Column:
anchors.centerIn: parent
Behavior on y {
NumberAnimation { duration: 1000 }
}
But the y position change is still not animated. How to achieve this?
I added another Item element which holds the Column. This allows you to set a Behavior on the item's height property and is what you're looking for:
import QtQuick 2.4
import QtQuick.Controls 1.3
ApplicationWindow {
width: 640
height: 480
visible: true
Item {
id: container
width: col.width
height: col.height
anchors.centerIn: parent
property int animationDuration: 200
Behavior on height {
PropertyAnimation {
duration: container.animationDuration
}
}
Column {
id: col
spacing: 2
focus: true
Rectangle { color: "red"; width: 50; height: 50 }
Rectangle { id: greenRect; color: "green"; width: 20; height: 50 }
Rectangle { color: "blue"; width: 50; height: 20 }
move: Transition {
NumberAnimation { properties: "x,y"; duration: container.animationDuration }
}
Keys.onSpacePressed: greenRect.visible = !greenRect.visible
}
}
}
Hope this helps!
Property changes induced by anchors don't seem to trigger Behaviours.
As a workaround, manually center the Column:
import QtQuick 2.2
Rectangle {
width: 640
height: 480
Column {
spacing: 2
anchors.horizontalCenter: parent.horizontalCenter
y: (parent.height - height) / 2
Behavior on y {
NumberAnimation { duration: 1000 }
}
Rectangle { color: "red"; width: 50; height: 50 }
Rectangle { id: greenRect; color: "green"; width: 20; height: 50 }
Rectangle { color: "blue"; width: 50; height: 20 }
move: Transition {
NumberAnimation { properties: "x,y"; duration: 1000 }
}
focus: true
Keys.onSpacePressed: greenRect.visible = !greenRect.visible
}
}

How to create scrollbar in QtQuick 2.0?

I am trying to create a scrollbar in QtQuick 2.0,
I found that Scrollbar component is available in QtQuick 1.0 but I can't find such component in QtQuick 2.0. How can I create scrollbar for ListView in QtQuick 2.0?
Any help? Thanks in advance.
ScrollBar/ScrollIndicator is easy to do, and the code would be identical in QQ1 or QQ2 (except the import) :
///////// ScrollBar.qml //////////////
import QtQuick 2.0;
Item {
id: scrollbar;
width: (handleSize + 2 * (backScrollbar.border.width +1));
visible: (flickable.visibleArea.heightRatio < 1.0);
anchors {
top: flickable.top;
right: flickable.right;
bottom: flickable.bottom;
margins: 1;
}
property Flickable flickable : null;
property int handleSize : 20;
function scrollDown () {
flickable.contentY = Math.min (flickable.contentY + (flickable.height / 4), flickable.contentHeight - flickable.height);
}
function scrollUp () {
flickable.contentY = Math.max (flickable.contentY - (flickable.height / 4), 0);
}
Binding {
target: handle;
property: "y";
value: (flickable.contentY * clicker.drag.maximumY / (flickable.contentHeight - flickable.height));
when: (!clicker.drag.active);
}
Binding {
target: flickable;
property: "contentY";
value: (handle.y * (flickable.contentHeight - flickable.height) / clicker.drag.maximumY);
when: (clicker.drag.active || clicker.pressed);
}
Rectangle {
id: backScrollbar;
radius: 2;
antialiasing: true;
color: Qt.rgba(0.5, 0.5, 0.5, 0.85);
border {
width: 1;
color: "darkgray";
}
anchors { fill: parent; }
MouseArea {
anchors.fill: parent;
onClicked: { }
}
}
MouseArea {
id: btnUp;
height: width;
anchors {
top: parent.top;
left: parent.left;
right: parent.right;
margins: (backScrollbar.border.width +1);
}
onClicked: { scrollUp (); }
Text {
text: "V";
color: (btnUp.pressed ? "blue" : "black");
rotation: -180;
anchors.centerIn: parent;
}
}
MouseArea {
id: btnDown;
height: width;
anchors {
left: parent.left;
right: parent.right;
bottom: parent.bottom;
margins: (backScrollbar.border.width +1);
}
onClicked: { scrollDown (); }
Text {
text: "V";
color: (btnDown.pressed ? "blue" : "black");
anchors.centerIn: parent;
}
}
Item {
id: groove;
clip: true;
anchors {
fill: parent;
topMargin: (backScrollbar.border.width +1 + btnUp.height +1);
leftMargin: (backScrollbar.border.width +1);
rightMargin: (backScrollbar.border.width +1);
bottomMargin: (backScrollbar.border.width +1 + btnDown.height +1);
}
MouseArea {
id: clicker;
drag {
target: handle;
minimumY: 0;
maximumY: (groove.height - handle.height);
axis: Drag.YAxis;
}
anchors { fill: parent; }
onClicked: { flickable.contentY = (mouse.y / groove.height * (flickable.contentHeight - flickable.height)); }
}
Item {
id: handle;
height: Math.max (20, (flickable.visibleArea.heightRatio * groove.height));
anchors {
left: parent.left;
right: parent.right;
}
Rectangle {
id: backHandle;
color: (clicker.pressed ? "blue" : "black");
opacity: (flickable.moving ? 0.65 : 0.35);
anchors { fill: parent; }
Behavior on opacity { NumberAnimation { duration: 150; } }
}
}
}
}
To use it :
import QtQuick 2.0;
Rectangle {
width: 400;
height: 300;
ListView {
id: list;
anchors.fill: parent;
model: 100;
delegate: Rectangle {
height: 50;
width: parent.width;
color: (model.index %2 === 0 ? "darkgray" : "lightgray");
}
}
ScrollBar {
flickable: list;
}
}
Enjoy !
Loved the solution by TheBootroo (+1 for him!) but found his solution only few days ago, by following a comment to a recent question.
Meanwhile, I've independently developed mine for a project I was working on and I'm going to share such a solution here. Hope it can be useful. :)
My scrollbar has a (sort of) "OS X feel" (intended) so e.g. it does not include scrolling arrows on the sides.
Here is the code:
import QtQuick 2.0
Item {
id: scrollbar
property Flickable flk : undefined
property int basicWidth: 10
property int expandedWidth: 20
property alias color : scrl.color
property alias radius : scrl.radius
width: basicWidth
anchors.right: flk.right;
anchors.top: flk.top
anchors.bottom: flk.bottom
clip: true
visible: flk.visible
z:1
Binding {
target: scrollbar
property: "width"
value: expandedWidth
when: ma.drag.active || ma.containsMouse
}
Behavior on width {NumberAnimation {duration: 150}}
Rectangle {
id: scrl
clip: true
anchors.left: parent.left
anchors.right: parent.right
height: flk.visibleArea.heightRatio * flk.height
visible: flk.visibleArea.heightRatio < 1.0
radius: 10
color: "gray"
opacity: ma.pressed ? 1 : ma.containsMouse ? 0.65 : 0.4
Behavior on opacity {NumberAnimation{duration: 150}}
Binding {
target: scrl
property: "y"
value: !isNaN(flk.visibleArea.heightRatio) ? (ma.drag.maximumY * flk.contentY) / (flk.contentHeight * (1 - flk.visibleArea.heightRatio)) : 0
when: !ma.drag.active
}
Binding {
target: flk
property: "contentY"
value: ((flk.contentHeight * (1 - flk.visibleArea.heightRatio)) * scrl.y) / ma.drag.maximumY
when: ma.drag.active && flk !== undefined
}
MouseArea {
id: ma
anchors.fill: parent
hoverEnabled: true
drag.target: parent
drag.axis: Drag.YAxis
drag.minimumY: 0
drag.maximumY: flk.height - scrl.height
preventStealing: true
}
}
}
And here is the code to use it. All the fields are optional expect for the flickable, obviously. Values set are the default ones:
ScrollBar {
flk: privacyFlick
radius: 10 // Optional
basicWidth: 10 // Optional
expandedWidth: 20 // Optional
color: "grey" // Optional
}
I think this will do the trick
http://qt-project.org/doc/qt-5.1/qtquickcontrols/qml-qtquick-controls1-scrollview.html
import QtQuick 2.0
import QtQuick.Controls 1.0
ScrollView{
ListView {
...
}
}
Qt 5.6 introduces new controls as the technical preview "Qt Labs Controls". Among other stuff, the controls introduce a built-in ScrollBar type (interactive) and ScrollIndicator type (not interactive).
In Qt 5.7 new controls exited technical preview and are now renamed "Quick Controls 2", to stress the fact that they superseed the previous controls.
If you are using Qt 5.6, which is an LTS version and will be around for quite sometime, ScrollBar can be used as follows:
import QtQuick 2.6
import Qt.labs.controls 1.0
import QtQuick.Window 2.2
ApplicationWindow {
visible: true
width: 400
height: 600
Flickable {
anchors.fill: parent
contentWidth: image.width
contentHeight: image.height
//ScrollIndicator.vertical: ScrollIndicator { } // uncomment to test
ScrollBar.vertical: ScrollBar { }
ScrollBar.horizontal: ScrollBar { }
Image {
id: image
source: "http://i.ytimg.com/vi/tntOCGkgt98/maxresdefault.jpg"
}
}
}
Whereas in Qt 5.7 and onward you can use ScrollBar or ScrollIndicator as follows:
import QtQuick 2.6
import QtQuick.Controls 2.0
import QtQuick.Window 2.2
ApplicationWindow {
visible: true
width: 600
height: 300
Flickable {
anchors.fill: parent
contentWidth: image.width
contentHeight: image.height
ScrollIndicator.vertical: ScrollIndicator { }
//ScrollBar.vertical: ScrollBar { } // uncomment to test
Image {
id: image
source: "http://s-media-cache-ak0.pinimg.com/736x/92/9d/3d/929d3d9f76f406b5ac6020323d2d32dc.jpg"
}
}
}
Usage syntax is pretty much the same whereas a major refactoring occured in the styling code as can be seen in e.g. Labs Controls ScrollIndicator customization page in comparison to Quick Controls 2 ScrollIndicator customization page.

Resources