Attribute parent dynamically to a QML component based in a condition - qt

How to attribute a parent dynamically when the QML component is being created based in a condition?
Example:
//FirstFile.qml
SecondFile{
Rectangle {
id: bodyRect
}
}
//SecondFile.qml
Rectangle{
id: rectangleId
Flickable{
id: flickableId
}
}
In this example the parent of bodyRect is rectangleId.
How to attribute the flickableId as a parent of bodyRectif a condition is true ?

Well, it really depends on what you actually want to achieve, which is totally unclear from the question as it stands right now.
If you use dynamic object instantiation, you can simply pass the desired parent to the function:
someComponent.createObject(condition ? parent1 : parent2)
Additionally, you can change the visual parent of an object based on a condition:
property bool cond: false
property Rectangle rect: Rectangle {
Rectangle {
parent: cond ? redrect : bluerect
anchors.centerIn: parent
width: 50
height: 50
color: "blue"
}
}
MouseArea {
anchors.fill: parent
onClicked: cond = !cond
}
Row {
Rectangle {
id: redrect
width: 200
height: 200
color: "red"
}
Rectangle {
id: bluerect
width: 200
height: 200
color: "green"
}
}
The blue rectangle will be dynamically reparented to either the red or the green rectangle as cond changes.
Keep in mind that you cannot really do stuff across different files, unless the objects happen to represent actual instances that have visibility in the object tree.

Related

qml components disappearing after enabeling layers

I have a Component for an sddm theme. At the moment I use the theme dark sugar as the base theme. The component looks like the following:
Item {
id: hexagon
property color color:"yellow"
property int radius: 30
//layer.enabled: true
//layer.samples: 8
Shape {
//... Here some Positioning and other Stuff
ShapePath {
//... Here some Options and Pathlines
}
}
}
This works fine, but as soon as I uncomment both layer settings the component disappears. Does this happen, because I load the component like this:
Pane {
...
Item {
...
MyComponent {
z: 1
}
}
}
Nor the Pane or the Item use layer but most Components in the Item use the z: 1 property.
As iam_peter says, the default width and height properties of any Item are 0, and layer.enabled sets the size of the offscreen texture to the item size. By default, the scene graph doesn't do any clipping: a child item can populate scene graph nodes outside its parent's bounds. But when you confine the children's rendering to a specific offscreen texture, anything that doesn't fit is clipped. Here's a more interactive example to play with this:
import QtQuick
import QtQuick.Controls
Rectangle {
width: 640
height: 480
Column {
CheckBox {
id: cbLE
text: "layer enabled"
}
Row {
spacing: 6
TextField {
id: widthField
text: layerItem.width
onEditingFinished: layerItem.width = text
}
Label {
text: "x"
anchors.verticalCenter: parent.verticalCenter
}
TextField {
id: heightField
text: layerItem.height
onEditingFinished: layerItem.height = text
}
}
}
Rectangle {
id: layerItem
x: 100; y: 100
border.color: "black"; border.width: 2
layer.enabled: cbLE.checked
Rectangle {
width: 100
height: 100
color: "tomato"
opacity: 0.5
}
Text {
text: "this text will get clipped even when layer size is defined"
}
}
}
You can use renderdoc to see how the rendering is done; for example you can see the texture that is created by enabling the layer.
This is a small reproducible example:
import QtQuick
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
Item {
//width: 200
//height: 200
//layer.enabled: true
Rectangle {
width: 100
height: 100
color: "red"
}
}
}
I suspect that if you don't set a size on the Item on which you want to enable the layer (layer.enabled: true), it will have a size of 0. Hence the offscreen buffer has a size of 0.
As a side note, this works without layer, because the clip property of an Item by default is set to false. So it won't clip to the bounds of its parent.

Draggable item get hidden behind other UI elements - Qt Qml

In my application window I have two ItemPanels which is orgnized inside a RawLayout.
Item {
RowLayout {
anchors.fill: parent
spacing: 1
ItemPanel {
Layout.preferredWidth: 250
Layout.fillHeight: true
panelHeader: "Components"
DraggableItem {
width: 100; height: 100;
}
}
ItemPanel {
Layout.preferredWidth: 250
Layout.fillHeight: true
panelHeader: "Actions"
}
}
}
The Components panel contains DraggableItems. Droppable area is the Actions panel. But if I tried to drag an DraggableItem to the Actions panel, it will be hidden while I'm dragging it.
DraggableItem
Item {
id: root
property string colorKey: "red"
width: 64; height: 64
MouseArea {
id: mouseArea
width: 64; height: 64
anchors.centerIn: parent
drag.target: tile
onReleased: parent = tile.Drag.target !== null ? tile.Drag.target : root
Rectangle {
id: tile
width: 64; height: 64
anchors.verticalCenter: parent.verticalCenter
anchors.horizontalCenter: parent.horizontalCenter
color: colorKey
Drag.keys: [ colorKey ]
Drag.active: mouseArea.drag.active
Drag.hotSpot.x: 32
Drag.hotSpot.y: 32
states: State {
when: mouseArea.drag.active
ParentChange { target: tile; parent: root }
AnchorChanges { target: tile; anchors.verticalCenter: undefined; anchors.horizontalCenter: undefined }
}
}
}
}
I was thinking adding a transparent layer and change the parent to it while dragging but I have no idea how to add a new layer on top of everything. Any other workarounds for this?
The easiest way would be to change the z-value of the ItemPanel with the panelHeader: "Components" to something greater than the siblings. Then automatically, all the children will be layered above them, too.
Reparenting is also a good solution. If you use ApplicationWindow as root object in your project, you don't even need to create add a new layer - it is already there.
You can use the attached property ApplicationWindow to reparent your draggable to ApplicationWindow.overlay. The only challange left is, that you need to specify the right position. You can use mapToItem() and mapFromItem() for this.
If you don't have ApplicationWindow as root, you can add a regualr Item as a child to your root and set the z-value to be the greates among its siblings. Then you assing it an id. If you don't shadow this id (having the same name for other identifiers, beeing resolved with higher priority) you can adress this Item from wherever. See more on this here.

Qt QML: Get reference to object emitting a signal

I have a screen with some rectangles which can contain text. The text content of these rectangles should be allowed to change through clicking on buttons in the screen where this component is used. The problem I am having is how to know in the screen which uses this component which instance is selected. I thought about solving this via emitting a signal, which transmits the id of the instance as reference, but it seems this does not work. How could this be accomplished? Here my custom rectangle component
Rectangle {
id: root
width: 50
height: 50
color: "#000000"
anchors.verticalCenter: parent.verticalCenter
border.color: "#555555"
property int value: 0
signal sendId(Item)
Text {
id: displayed_text
color: "#ffffff"
text: root.value
anchors.horizontalCenter: parent.horizontalCenter
anchors.verticalCenter: parent.verticalCenter
horizontalAlignment: Text.AlignHCenter
verticalAlignment: Text.AlignVCenter
font.pixelSize: 15
}
MouseArea {
id: mouseArea
anchors.fill: parent
onClicked: {
root.border.color="#222222"
root.sendId(root.id)
}
}
}
and here the file where other buttons should change the content of the custom component:
property Item selected: myRectangle
function changeSelected(value) {
selected.value=5
}
function setSelected(it) {
root.selected=it
}
MyRectangle {
id: myRectangle
Component.onCompleted: {
myRectangle.sendId.connect(tempNumber.setSelected)
}
}
MyRectangle {
id: myRectangle1
Component.onCompleted: {
myRectangle1.sendId.connect(tempNumber.setSelected)
}
}
MyRectangle {
id: myRectangle2
Component.onCompleted: {
myRectangle2.sendId.connect(tempNumber.setSelected)
}
}
root.sendId(root.id)
The id is not a regular property. Don't use it as such. The purpose of the id is to get you a reference, with which you can refer to a particular object, so all you really need is:
root.sendId(root)
And if root is your qml file root object, sendId(root) would work too as long as sendId is not shadowed, root members can be referenced directly, keep in mind this only applies to the root object, it won't work for a object that is a direct or indirect parent but not root.
It is recomended practice to abstain from giving everything an id - only use ids when you really need to reference a particular object and no other way exists.
Another thing you are missing is that unlike JS functions, you do have to provide some typing for a signal. You can still use var and pass anything, but usually it is more efficient to narrow down the scope. So you need type and identifier:
signal sendId(Item item)
This way you can access item in the signal handlers, so you can avoid the awkward imperative connection syntax, so instead you can simply:
MyRectangle {
onSendId: tempNumber.setSelected(item)
}
However, I'd say your design is not optional. Signals are supposed to be employed when you aim for generality and reuse. Your usage scenario is more specific, thus the usage of signals can be avoided altogether:
// Rect.qml
Rectangle {
width: 50
height: 50
color: manager.selected === this ? "red" : "blue"
MouseArea {
anchors.fill: parent
onClicked: manager.selected = parent
}
}
// main.qml
Window {
id: manager
visible: true
width: 600
height: 300
property Item selected: null
Row {
spacing: 2
Repeater {
model: 10
delegate: Rect {}
}
}
}
As the following example shows, you can directly access objects by id as long as they can be found down the object tree. The same applies to properties, however while the id will work for any object down the tree, properties will only work if they are declared in the root object of the particular qml file.

Warnings in QML: Delegate in separate file and access on model item properties

The following code works and shows my items correctly, but I get the warning
qrc:/TableDelegate.qml:24: ReferenceError: name is not defined
I think it is because the ListView tries to access the model when it is empty and can not reference the item properties. I assume I am not doing to it correctly but I do not know how to do it better.
So my question is: how to get rid of the warning by doing it the right way?
TableDelegate.qml:
import QtQuick 2.0
import QtQuick.Layouts 1.1
Item {
property color bgcolor: 'transparent'
property alias box: rowBox
height: 40
width: parent.width
Rectangle {
id: rowBox
anchors.fill: parent
color: bgcolor
RowLayout {
anchors.fill: parent
Rectangle {
id: tableNameColumn
color: 'transparent'
Layout.fillHeight: true
Layout.fillWidth: true
Text {
anchors.centerIn: parent
color: textcolor
text: name // <--- here is `name`
}
}
// More Columns ...
}
}
MouseArea {
anchors.fill: parent
onClicked: {
view.currentIndex = index
}
}
}
And I use it like this
TableView.qml:
// ...
ListModel {
id: model
}
ListView {
id: view
model: model
anchors.fill: parent
highlight: delegate_highlighted
highlightFollowsCurrentItem: true
delegate: delegate
}
Component {
id: delegate
TableDelegate {
bgcolor: 'transparent';
}
}
Component {
id: delegate_highlighted
TableDelegate {
bgcolor: 'lightsteelblue'
box.border.color: 'black'
box.radius: 3
}
}
// ...
You use a TableDelegate for the highlight. That is wrong.
The ListView creates 1 instance of the highlight item, that will be drawn as a background for the currently selected item, It may also move between items as transition when the current item changes. It should only be a rectangle or whatever you want to use.
In your example, the highlight item is a full delegate, that wants to access model data, which it cannot.

Add elements dynamically to SplitView in QML

I am working with QML and I want to add elements to SplitView dynamically eg. onMouseClick, but so far I didn't find the answer.
What I've found out so far is that the SplitView has it's default property set to it's first child's data property. So I guess I should try and add new dynamically created components with the parent set to that child (splitView1.children[0]). Unfortunately that doesn't work either. What is more the number of children of that first child is zero after the component has finished loading (seems like the SplitLayout's Component.onCompleted event calls a function that moves those children somewhere else). Thus the added children do not render (and do not respond to any of the Layout attached properties).
Please see the following code snippet:
import QtQuick 2.1
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.0
ApplicationWindow {
width: 600
height: 400
SplitView {
anchors.fill: parent
Rectangle {
id: column
width: 200
Layout.minimumWidth: 100
Layout.maximumWidth: 300
color: "lightsteelblue"
}
SplitView {
id: splitView1
orientation: Qt.Vertical
Layout.fillWidth: true
Rectangle {
id: row1
height: 200
color: "lightblue"
Layout.minimumHeight: 1
}
// Rectangle { //I want to add Rectangle to splitView1 like this one, but dynamicly eg.onMouseClick
// color: "blue"
// }
}
}
MouseArea {
id: clickArea
anchors.fill: parent
onClicked: {
console.debug("clicked!")
console.debug("len: " + splitView1.__contents.length); // __contents is the SplitView's default property - an alias to the first child's data property
var newObject = Qt.createQmlObject('import QtQuick 2.1; Rectangle {color: "blue"}',
splitView1, "dynamicSnippet1"); //no effect
// var newObject = Qt.createQmlObject('import QtQuick 2.1; import QtQuick.Layouts 1.0; Rectangle {color: "blue"; width: 50; height: 50}',
// splitView1, "dynamicSnippet1"); //rectangle visible, but not in layout(?) - not resizeable
}
}
}
Is there any way I can make the dynamically created components render properly in the SplitView as the statically added ones?
It appears that the API does not provide support for dynamic insertion of new elements. Even if you do get it to work it would be a hack and might break with future releases. You may need to roll your own control to mimic the behavior you want. Ideally it should be backed by some sort of model.
As of QtQuick Controls 1.3, SplitView has an addItem(item) method.
you have to use the Loader for load dinamicaly objects. in onClicked handle you have to declare sourceComponent property to change the source of the Loader, something like this:
ApplicationWindow {
width: 600
height: 400
SplitView {
anchors.fill: parent
Rectangle {
id: column
width: 200
Layout.minimumWidth: 100
Layout.maximumWidth: 300
color: "lightsteelblue"
}
SplitView {
id: splitView1
orientation: Qt.Vertical
Layout.fillWidth: true
Rectangle {
id: row1
height: 200
color: "lightblue"
Layout.minimumHeight: 1
}
Loader {
id:rect
}
}
}
MouseArea {
id: clickArea
anchors.fill: parent
onClicked: {
console.debug("clicked!")
console.debug("len: " + splitView1.__contents.length) // __contents is the SplitView's default property - an alias to the first child's data property
rect.sourceComponent = algo
}
}
Component {
id:algo
Rectangle {
anchors.fill: parent
color: "blue"
}
}
}
I saw the source code of SplitView, it calculate each split region when Component.onCompleted signal. So I think that is a key point. No matter how you do (insert, dynamic create). The region won't be reset after you insert a new region for split.

Resources