Does setting an component's width or height to zero has the same effect as setting its visible property to false?
An example use-case:
I have an item, which slides into the window. The sliding happens by animating its height from 0 to x and when I dismiss this item from x to 0. Don't want to go in depth why I am not animating the position of the item instead. When the item has 0 height, should I set its visible property to false or it doesn't make any difference?
Not really, unless you clip. And it is better to avoid clipping as much as possible.
An Item with zero size will still have its children visible.
Whereas setting visible to false will hide the entire object tree.
In your particular case it seems like it doesn't matter as long as it doesn't cause you to have unwanted visible leftovers. You certainly do not want to have a binding such as visible: height as that would needlessly execute on every step of the animation.
Just to be on the safe side, you can install handlers on the animation to toggle visibility:
// in the animation
onStarted: if (!item.height) item.visible = true // show if start at 0
onStopped: if (!item.height) item.visible = false // hide if end at 0
This will avoid the continuous reevaluations you'd get if you bind visibility to height directly, but will still ensure visibility on before your object begins expanding and off after it has finished contracting.
As dtech already pointed out, the dimensions of the root node of a component do not automatically represent the dimensions of the underlying object tree. As an example take this:
Item {
id: root
Text {
id: txt
text: 'some text produces implicit width'
}
}
In this example the text of txt will be shown, though the dimensions of root are width: 0; height: 0.
As dtech already mentioned, you might set clip to true, but this is not advisable, as then it would be passed to the renderer, which renders the Item and its tree and finally applies clipping to it - in a seperate batch.
If you have something like that:
Item {
Rectangle {
anchors.fill: parent
color: 'red'
}
}
The renderer would do nothing extra when rendering, as it could be processed in the same batch as the rest. However as a developer it is hard to tell, whether something is visible when the size is set to 0 or not. Therefore it is adivsable to always set visible properly.
We might simply set
visible: width > 0 && height > 0 && opacity > 0
which works fine, as long as we don't animate on any of those properties or change them frequently. At least for animations we might have good knowledge, when the any of those properties might become 0 and use this information to reduce the amount of evaluations.
The nice thing about QML is, that the logical expression is evaluated from the left to the right, which means in our last example:
If width === 0 and height changes, it wont trigger reevaluation
If height === 0 and width changes, each change triggers reevaluation.
This means, we need to put the most stable condition first. This might be our information about when any of those values might change. I propose, using the animation.running property, to prevent reevaluation of the binding, while the animation is running.
Let's take a more complete example: Upon click, this Rectangle will shrink from width: 800 to width: 0 - which shall set it invisible.
Or three additional properties binding1, binding2, binding3 are bound to expressions, that we might use to set visible. When ever a particular part of the binding is reeavluated, we log this.
Rectangle {
id: rect
color: 'red'
width: 800
height: 600
NumberAnimation {
id: ani1
target: rect
property: 'width'
from: 800
to: 0
duration: 3000
}
}
MouseArea {
anchors.fill: parent
onClicked: ani1.running = true
}
property bool binding1: {console.log("1", !rect.width); return !rect.width}
property bool binding2: {!ani1.running && (function() { console.log("2", !rect.width); return !rect.width })()}
property bool binding3: {(function() { console.log("3", !rect.width); return !rect.width })() && !ani1.running}
// equivalent, stripped of the logging:
// property bool binding1: !rect.width
// property bool binding2: !ani1.running && !rect.width
// property bool binding3: !rect.width && !ani1.running
As we can see, binding1 is constantly reevaluated, when ever the width changes. This is not desirable.
We can see, that binding2 is only evaluated once at creation, and whenever ani stops running.
In binding3 we have it the other way around and we first evaluate the width, and then whether the ani is running. This means, we have a reevaluation whenever the width is changing.
We could also use the signal handlers ani.onStarted and ani.onStopped and explicitly set the visiblity then, but that would not be declarative and QML encourages you to always strive to stay declarativ.
Related
I want to specify anchors for all sides using anchors.margins, but set a side anchor, like anchors.leftMargin to a different value.
For example:
Rectangle {
id: rect
width: 100; height: 100
color: "black"
Rectangle {
anchors {
fill: parent
leftMargin: 0
margins: 30
}
color: "lime"
}
}
Which shows:
It seems to work, but is this a feature or a bug waiting to happen? Isn't margins a shortcut that sets all side anchor margins and the fact that it works just due to the order in which bindings are evaluated? If someone modifies the code might anchors.margins overwrite the leftMargin property?
Anchors.margins provides the default value for the more specific margin properties. So, what you are doing is safe and supported.
It is safe to set side anchors and anchors.margins together.
anchors.margins, anchors.leftMargin, anchors.topMargin, anchors.rightMargin, and anchors.bottomMargin are all separate properties. The default value for all side anchors is anchors.margins; assigning undefined to a side anchor reverts it to the anchors.margins value.
What is the difference between width/height and implicitWidth/Height in QML? When should one set the implicit dimensions instead of the regular? When should one ask the implicit dimensions instead of the regular from a component/item?
Generally, usage of implicitHeight/Width only makes sense within reusable components.
It gives a hint, of the natural size of the Item without enforcing this size.
Let's take a Image as an example. The natural size of the image would map one pixel from the image file to one pixel on the screen. But it allows us to stretch it, so the size is not enforced and can be overridden.
Let's say now, we want to have a gallery with pictures of unknown dimension, and we don't want to grow but only shrink them if necessary. So we need to store the natural size of the image. That is, where the implicit height comes into play.
Image {
width: Math.max(150, implicitWidth)
height: Math.max(150, implicitHeight)
}
In custom components, you have a choice on how to define the sizes.
The one choice is, to have all dimensions relative to the components root-node, maybe like this:
Item {
id: root
Rectangle {
width: root.width * 0.2
height: root.height * 0.2
color: 'red'
}
Rectangle {
x: 0.2 * root.width
y: 0.2 * root.height
width: root.width * 0.8
height: root.height * 0.8
color: 'green'
}
}
In this case, there is no natural size of the object. Everything works out perfectly for each size you set for the component.
On the other hand, you might have an object, that has a natural size - that happens, e.g. if you have absolute values in it
Item {
id: root
property alias model: repeater.model
Repeater {
id: repeater
delegate: Rectangle {
width: 100
height: 100
x: 102 * index
y: 102 * index
}
}
}
In this example you should provide the user with information about the natural size, where the content does not protude the item. The user might still decide to set a smaller size and deal with the protrusion, e.g. by clipping it, but he needs the information about the natural size to make his decision.
In many cases, childrenRect.height/width is a good measure for the implcitHeight/Width, but there are examples, where this is not a good idea. - e.g. when the content of the item has x: -500.
A real life example is the Flickable that is specifically designed to contain larger objects than its own size. Having the size of the Flickable to be equal to the content would not be natural.
Also be careful, when using scale in custom components, as the childrenRect will not know about the scaling.
Item {
id: root
implicitWidth: child.width * child.scale
implicitHeight: child.height * child.scale
Rectangle {
id: child
width: 100
height: 100
scale: 3
color: 'red'
}
}
And to your comment: I just don't understand why it is better to set implicitWidth/Height instead of setting width/height of a component's root dimension.
implicitWidht/Height are not a necessety - QtQuick could do without them. They exist for convenience and shall be convention.
Rule of Thumb
When you want to set dimension of a root node of a reusable component, set implicitWidth/Height.
In some cases, set it for non-root-nodes, if the nodes are exposed as a property.
Do so only, if you have a reason for it (many official components come without any).
When you use a component, set width/height.
I don't have the definitive answer but I can tell you what I found out. First, from the documentation:
implicitWidth : real
Defines the natural width or height of the Item if no width or height
is specified.
The default implicit size for most items is 0x0, however some items
have an inherent implicit size which cannot be overridden, for
example, Image and Text.
but less informative for width:
width
Defines the item's position and size.
The width and height reflect the actual size of the item in the scene. The implicit size is some kind of inherent property of the item itself.1
I use them as follows: When I create a new item and it can be resized, I set an implicit size inside the object2. When I'm using the object, I often set the real size explicitly from the outside.
The implicit size of an object can be overridden by setting height and width.
an example: TextWithBackground.qml
Item {
implicitWidth: text.implicitWidth
implicitHeight: text.implicitHeight
// the rectangle will expand to the real size of the item
Rectangle { anchors.fill: parent; color: "yellow" }
Text { id: text; text: "Lorem ipsum dolor..." }
}
an example: MyWindow.qml
Item {
width: 400
height: 300
TextWithBackground {
// half of the scene, but never smaller than its implicitWidth
width: Math.max(parent.width / 2, implicitWidth)
// the height of the element is equal to implicitHeight
// because height is not explicitly set
}
}
1) For some elements, like Text, the implicit height depends on the (not-implicit) width.
2) The implicit size usually depends on the implicit size of its children.
Implicit size is supposed to be used when calculating size of an item based on its contents. Whereas setting width or height on a parent item may affect the size of its children it should never be a case, when you set implicit size.
Rule of thumb
Implicit size should only "bubble up", i.e. children should never
lookup for implicit size of their parent to calculate their own
implicit size, neither parent should try to force implicit size of its
children.
If you would try to set width on a component similar to layout, that initially calculates its width from the width (rather than implicitWidth) of its child item and that child is affected by the size of a parent, you would end up with a binding loop.
This is why the property exists - to break cyclic dependencies when calculating size of an item based on its contents.
I have a window with a QML image in it that needs to flash, so I use a Timer and toggle the visible flag every 500ms. The image has its size, max size, min size and preferred size set to 24. However, the widget next to it in the RowLayout moves backwards and forwards when the visibility changes. How can I make the icon flash without invalidating the layout?
Set opacity: 0 instead of visible: false.
Or, alternatively, do something like this:
RowLayout {
// ...
Item {
width: 24
height: 24
Image {
anchors.fill: parent
// ...
}
}
... and just toggle the visible property of the Image, like you've been doing.
Consider this example:
import QtQuick 2.7
import QtQuick.Controls 2.0
ApplicationWindow {
id: appWindow
width: 1024
height: 800
visible: true
Rectangle {
id: rect1
property bool active: true
opacity: active ? 1 : 0
height: 300 * opacity
width: 300 * opacity
Behavior on opacity { NumberAnimation { duration: 1000 } }
MouseArea { anchors.fill: parent; onClicked: parent.active = false }
color: 'cornflowerblue'
}
Rectangle {
id: rect2
property bool active: true
x: 305
opacity: active ? 1 : 0
height: active ? 300 : 0
width: active ? 300 : 0
Behavior on opacity { NumberAnimation { duration: 1000 } }
Behavior on height { NumberAnimation { duration: 1000 } }
Behavior on width { NumberAnimation { duration: 1000 } }
MouseArea { anchors.fill: parent; onClicked: parent.active = false }
color: 'steelblue'
}
}
I have two Rectangles with the same observable behavior: when clicked, they fade both in opacity and size.
Internally, it differs in the amount of Animations, that are running concurrently - either 1 or 3:
As of now, I mainly use the pattern form rect1 and only in cases where the bindings would get unneccessarily complex rect2. However I wonder, if the animation system has some magic, that optimizes the animation of a single property, while the binding might be less performant.
In which usecases it is beneficial to use pattern rect1 and when it would be wiser to use the method of rect2?
EDIT There is also a third option which moves, what possible, to the render thread via OpacityAnimator. Now I can't bind to the opacity anymore, as it will jump to 0 at the end of the animation.
Rectangle {
id: rect3
property bool active: true
opacity: active ? 1 : 0
height: active ? 300 : 0
x: 610
width: height
Behavior on opacity { OpacityAnimator { duration: 1000 } }
Behavior on height { NumberAnimation { duration: 1000 } }
MouseArea { anchors.fill: parent; onClicked: parent.active = false }
color: 'dodgerblue'
}
EDIT 2 To adress the Answer of Ansh Kumar:
This is an excerpt from the QML Profiler. You can see, that during the animation of rect2 there are neither bindings nor JavaScript running, unlike during the times where height and width are (efficiently) bound to the opacity in rect1 or the width is (efficiently) bound to the height in rect3.
Further the source of the animations shows little trace of JS. I couldn't examine it into all it's depths, but it seems, that only a ScriptAction gets a QQMLScriptString and the rest has only the cost of converting the input from var to the right type (if a type is specified by using a concrete animation such as NumberAnimation).
Further, as far as I can see, there is not a loop per animation involved, but all animations feature some kind of update()-function or so, that is called (when running/registered) by a single loop (AnimationTimer). But this is where I am already unsure about.
Now the question remains: Is the implementation of the animations more efficient than the optimized JS environment especially as multiple objects are created and stuff.
There are two types of bindings in QML: optimized and non-optimized bindings. It is a good idea to keep binding expressions as simple as possible, since the QML engine makes use of an optimized binding expression evaluator which can evaluate simple binding expressions without needing to switch into a full JavaScript execution environment. These optimized bindings are evaluated far more efficiently than more complex (non-optimized) bindings. The basic requirement for optimization of bindings is that the type information of every symbol accessed must be known at compile time.
Bindings are quickest when they know the type of objects and properties they are working with. Animating a property will cause any bindings which reference that property to be re-evaluated. Usually, this is what is desired. The opacity, height and width in rect2 are re-evaluated into a full JavaScript execution environment whereas in rect1; width and height goes through an optimized binding expression evaluator and optimized to give more efficient binding since their type of object is known at compile time. Check binding and also animations for more details.
EDIT
You were right about evaluation being done in C++ environment. I found following informations.
Rendering engine should achieve a consistent 60 frames-per-second refresh rate. 60 FPS means that there is approximately 16 milliseconds (exactly 16.6667 milliseconds) between each frame in which processing can be done, which includes the processing required to upload the draw primitives to the graphics hardware. This shows that the animation is in sync with the vertical refresh, so once every 16.66 ms, and exactly once pr frame.
while (animationIsRunning) {
processEvents();
advanceAnimations();
paintQMLScene();
swapAndBlockForNextVSync();
}
So, in rect1 you have set duration: 1000 and binded height with opacity (height: 300 * opacity) similarly width with opacity, so binding should be called around 60 times ? If you see QML profiler output of statistics you will find following
As expected number of calls are around 60 (exactly 63). Now if you change duration to 2000, number of calls will be doubled.
Since, 300 * opacity has to be calculated, so QML should call JavaScript environment around 60 times (when duration: 1000)
As expected it was called around 60 times.
What about the NumberAnimation, is it implemented in JavaScript or C++ ? Definitely, you were right about it being implemented in C++, Here is the link to its declaration . So, in rect1 we have used NumberAnimation one time and in rect2 we have used it 3 times. So, total of 4 instances of NumberAnimation should be created.
So, rect1 has a total of around 120 bindings and JavaScript calls whereas in in rect2 there is no binding and JavaScript calls, so animation of rect2 should be faster, but the question is, will there be any significant improvements? Since, free version of QtCreator does not comes with CPU analyzer I was not able to study that part of the question (CPU Usage Qt). If anyone has commercial version of Qt, please update me about my hypothesis. I really think that rect2 is the best for usage as number of calls are reduced.
In QML, I want to create a text moving when the mouse in on it. When the mouse is not on it anymore, it should go back to its original position. The value of the variable 'toogle' in the code is true when my mouse is on the text, false when its not.
property real distance: myText.x
...
Text {
id: myText
property bool toogle
x:toogle?distance+2:distance
}
The problem is obviously that the value of distance will be increased when the mouse is on the text and that it will create a loop: the text will be always moving as long as the mouse is on it.
How can I save the value of the original x position of the text when it's created, and keep it unmodified to avoid having this undesired loop?
You could define a property and set it to a fixed value whenever the component loading is completed:
// Keep track of the original position.
property real originalPosition;
Component.onCompleted: {
originalPosition = myText.x;
}
I am a bit confused with your question though, do you want the text to keep moving or not whenever the mouse hovers over the text? The code you posted already contains a binding loop.
To detect mouse hovers you can define a MouseArea within your Text element and listen to the 'containsMouse' property to be able to reset the text's position:
MouseArea {
id: mouseArea
width: parent.width
height: parent.height
hoverEnabled: true
onContainsMouseChanged: {
console.log("Changed: " + containsMouse);
if (!containsMouse) {
myText.x = myText.originalPosition;
} else {
myText.x = mouseArea.containsMouse ? myText.originalPosition+2: myText.originalPosition;
}
}
}
This last implementation will only move the text 2 pixels whenever the text is hovered and back to the original position whenever the mouse stops hovering. It will NOT continuously move the text 2 pixels when hovered.