How to access inner item from parent in QML? [duplicate] - qt

The document said we cannot have the same ID in one file. That means we can have the same id in different file,right? I don't know the scope of ID in QML,so i write the code as following to test it.
//a.qml
Item {
id: a_item
x:20;
y:b_item.x // cannot access this id
y:b1.x1 // can access
Item {
id:a1
x:20
Component.onCompleted : a1.x //this a1 is a.qml's a1 not the a1 in main.qml
}
}
//b.qml
Item {
id: b_item
x:20;
property int x1: 30;
}
//main.qml
Item {
a {
id:a1
Component.onCompleted : b1.x = 1 //can access
}
b {
id:b1
}
function() {
a_item.x = 1; // cannot access this id
}
}
My question:
1.
What is the scope of ID in QML? In my test, the result shows that Item cannot access the id of its childen and his brother 's chilren, but can access his parent or brother, right?
2.
the same id in different file just i show in my code, no error and i worked. But how can i differentiate them.

The canonical answer would be:
The scope of ids is the component scope.
And the component scope is:
Each QML component in a QML document defines a logical scope. Each
document has at least one root component, but can also have other
inline sub-components. The component scope is the union of the object
ids within the component and the component's root object's properties.
Which itself is not overly informative on what the scope exactly is and how can you make optimal use of it. A tad more informative:
In QML, component instances connect their component scopes together to
form a scope hierarchy. Component instances can directly access the
component scopes of their ancestors.
Basically, each id in a qml file is implemented sort of like a property of that source's root item. Except it cannot be accessed via someobj.someId, only via someId.
Which means that this id can be accessed by any object that exists in the branch that extends from the root object thanks to qml's dynamic scoping.
That is as long as it is not shadowed by an identically named id or property.
a_item will be visible in a.qml as well as any object that exists in the branch its root Item grows.
It won't be visible from main.qml as that object is further down the tree, where a_item is not defined.
In the same line of thought, b1 can be accessed from a.qml because b1 is defined in main.qml which is where a.qml is instantiated. But b_item will
not be visible from there.
In fact, since a1 and b1 are defined in main.qml which is the root of the entire application tree, those two ids will be visible from every object of the application, as long as it is a part of the object tree and as long as the identifiers are not shadowed. Note that they will not be visible from singletons or parent-less objects, as those are not part of the application object tree.
obj tree a1 b1 a_item b_item
main.qml D D X X
a.qm V V D X
Item a1 V V V X
b.qml V V X D
D - defined here, V - visible here, X - not available
The same is true for properties, although dynamic scoping only works for properties that are defined for the qml file root element, unlike ids which are visible even if they are on a different sub-branch, which is why in the first sentence of this answer I put it as "implemented sort of a property of that source's root item":
Obj
Obj
Obj
id: objid
property objprop
CustomObj
So objid will be visible in CustomObj, but objprop will not be, since it is not an id and not defined in the root object. The id is identical to doing this:
Obj
property objid : _objid
Obj
Obj
id: _objid
All ids from a given sources are visible in the qml source root object's context and subsequently everything else that will eventually drop down to this context as it lookup fails to resolve the identifier in the "higher" contexts.
Finally, keep in mind the subtle trap - it is only possible to use ids across sources if you know for certain that your application will instantiate the objects in a compatible context tree.
For example:
A.qml {
id: objA
B { } // objA will be visible to this object
}
main.qml
A {
B {} // objA will NOT be visible to this object
}
B {} // objA will NOT be visible to this object
The trap continues - context tree comes before object tree - the context in which an object is created matters, and cannot be changed once set (puts certain limits on reparenting depending on context dependencies).
// ObjA.qml
Item {
id: objA
Component {
id: cm
ObjB {}
}
function create() { cm.createObject(objA) }
}
// ObjB.qml
Item {
Component.onCompleted: console.log(objA)
}
// main.qml
Component {
id: cm
Rect {}
}
Obj {
anchors.fill: parent
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.LeftButton | Qt.RightButton
onClicked: {
if (mouse.button === Qt.LeftButton) {
cm.createObject(parent)
} else {
parent.create()
}
}
}
}
As this practical example illustrates, even though in both cases the newly created object is parented to the same object that has the objA identifier, the object created in main.qml cannot resolve it, because it is created in a context where objA is still not defined, but it works if the object is created in the context of objA, and it will work even if it is burred even higher up the tree.
To put it in a more generic way, an id becomes visible in the context of the source's root object and remains visible in every subsequent sub-context until it is shadowed by an identically named object. Visibility cannot reach down the tree to contexts that exist before the context the id is defined in.
Note the subtle difference - a_item refers to an Item whereas a1 refers to an a. And since a1 is visible inside a.qml it will always refer to that one instance of a that is in main.qml, regardless of which instance of a you might be in, whereas a_item will refer to a different object for each different instance of a. a_item is "relative" and will be different in every different instance of a but a1 is absolute and will always refer to a specific instance of a. This is the case because a1 is a concrete instance whereas a_item is a type / prototype.
// Obj.qml
Item {
id: obj
Component.onCompleted: console.log(obj === oid)
}
// main.qml
Obj { } // false
Obj { id: oid } // true
Dynamic scoping of ids can be quite useful and cut the time it takes to implement a workaround to get access to the stuff you need. Which is also why it is a very good idea to give the id descriptive names rather than just main.
For example, if you have a manager that manages a number of views, each with a number of objects in them, you can quickly get access the respective view for each object and also get access to the manager without having to implement any additional stuff. The rule of thumb is that the manager must come first, then each view should be created in the context of the manager, not necessarily directly in it, but in it nonetheless, and each object should be created in the context of a view. And of course take care not to shadow over things. If you break that rule things will not resolve properly.
View.qml { id: view }
manager
view1
object // view is view1
view2
object // view is view2
view3
object // view is view3
Naturally, this makes sense only in specific purpose designs where you know what the general structure of the context tree is gonna be like. If you are making generic elements that may go just about anywhere, you should absolutely not be relying on accessing ids across sources, and you should implement a more generic usage interface via properties, aliases and whatnot.

Related

QML: Dynamic view re-ordering in original model

Implemented QML Dynamic View Ordering by Dragging View Items using this Qt tutorial: QML Dynamic View Ordering Tutorial. Original underlying model is QAbstractListModel descendant in our case. Model stores data in a QList<QObject*> objectList; field type. Works fine, however item ordering changed in proxy DelegateModel only.
How to change items order automatically in original underlying model as well for other C++ and QML consumers where order matters? Or I could we otherway access some resulted (sorted) List Model model from C++ somehow?
Thanks for any help!
In the QML Dynamic View Ordering Tutorial 3 example I've replaced visualModel.items.move() call with my ObjectListModel::move() method like this:
ObjectListModel : public QAbstractListModel:
void ObjectListModel::move(int from, int to)
{
if(0 <= from && from < count() && 0 <= to && to < count() && from != to) {
if(from == to - 1) // Allow item moving to the bottom
to = from++;
beginMoveRows(QModelIndex(), from, from, QModelIndex(), to);
objectList.move(from, to);
endMoveRows();
}
}
Delegate component:
DropArea {
anchors { fill: parent; }
onEntered: {
let from = drag.source.DelegateModel.itemsIndex
let to = mouseArea.DelegateModel.itemsIndex
objectListModel.move(from, to)
}
}
And above works perfectly for the ListView and ObjectListModel itself - I have checked: items (and therefore objects) are moved correctly, indexes are correct, C++ consumers works just fine and take new order into account correctly, etc.
However another consumer like MapItemView fails to use the model after beginMoveRows/endMoveRows calls: moved item disappeared on the map and other manipulations with an item crashes the app.
Map {
...
MapItemView {
model: objectListModel
delegate: SomeItemIndicator {
}
}
}
Reported QTBUG-81076 bug, which is confirmed.
Workaround:
Found workaround for now: created 2nd duplicate model which content will be replaced completely on every change in the 1st model on every add/delete/moving(reordering). Above works since beginResetModel/endResetModel works correctly for MapItemView. So MapItemView now utilizes only the 2nd model. So on every 1st model change this method is called for the 2nd model:
QObjectList ObjectListModel::swapObjectList(const QObjectList& newlist)
{
QObjectList oldlist(_objectList);
beginResetModel();
_objectList = newlist;
endResetModel();
return oldlist;
}

What is the scope of ID in QML?

The document said we cannot have the same ID in one file. That means we can have the same id in different file,right? I don't know the scope of ID in QML,so i write the code as following to test it.
//a.qml
Item {
id: a_item
x:20;
y:b_item.x // cannot access this id
y:b1.x1 // can access
Item {
id:a1
x:20
Component.onCompleted : a1.x //this a1 is a.qml's a1 not the a1 in main.qml
}
}
//b.qml
Item {
id: b_item
x:20;
property int x1: 30;
}
//main.qml
Item {
a {
id:a1
Component.onCompleted : b1.x = 1 //can access
}
b {
id:b1
}
function() {
a_item.x = 1; // cannot access this id
}
}
My question:
1.
What is the scope of ID in QML? In my test, the result shows that Item cannot access the id of its childen and his brother 's chilren, but can access his parent or brother, right?
2.
the same id in different file just i show in my code, no error and i worked. But how can i differentiate them.
The canonical answer would be:
The scope of ids is the component scope.
And the component scope is:
Each QML component in a QML document defines a logical scope. Each
document has at least one root component, but can also have other
inline sub-components. The component scope is the union of the object
ids within the component and the component's root object's properties.
Which itself is not overly informative on what the scope exactly is and how can you make optimal use of it. A tad more informative:
In QML, component instances connect their component scopes together to
form a scope hierarchy. Component instances can directly access the
component scopes of their ancestors.
Basically, each id in a qml file is implemented sort of like a property of that source's root item. Except it cannot be accessed via someobj.someId, only via someId.
Which means that this id can be accessed by any object that exists in the branch that extends from the root object thanks to qml's dynamic scoping.
That is as long as it is not shadowed by an identically named id or property.
a_item will be visible in a.qml as well as any object that exists in the branch its root Item grows.
It won't be visible from main.qml as that object is further down the tree, where a_item is not defined.
In the same line of thought, b1 can be accessed from a.qml because b1 is defined in main.qml which is where a.qml is instantiated. But b_item will
not be visible from there.
In fact, since a1 and b1 are defined in main.qml which is the root of the entire application tree, those two ids will be visible from every object of the application, as long as it is a part of the object tree and as long as the identifiers are not shadowed. Note that they will not be visible from singletons or parent-less objects, as those are not part of the application object tree.
obj tree a1 b1 a_item b_item
main.qml D D X X
a.qm V V D X
Item a1 V V V X
b.qml V V X D
D - defined here, V - visible here, X - not available
The same is true for properties, although dynamic scoping only works for properties that are defined for the qml file root element, unlike ids which are visible even if they are on a different sub-branch, which is why in the first sentence of this answer I put it as "implemented sort of a property of that source's root item":
Obj
Obj
Obj
id: objid
property objprop
CustomObj
So objid will be visible in CustomObj, but objprop will not be, since it is not an id and not defined in the root object. The id is identical to doing this:
Obj
property objid : _objid
Obj
Obj
id: _objid
All ids from a given sources are visible in the qml source root object's context and subsequently everything else that will eventually drop down to this context as it lookup fails to resolve the identifier in the "higher" contexts.
Finally, keep in mind the subtle trap - it is only possible to use ids across sources if you know for certain that your application will instantiate the objects in a compatible context tree.
For example:
A.qml {
id: objA
B { } // objA will be visible to this object
}
main.qml
A {
B {} // objA will NOT be visible to this object
}
B {} // objA will NOT be visible to this object
The trap continues - context tree comes before object tree - the context in which an object is created matters, and cannot be changed once set (puts certain limits on reparenting depending on context dependencies).
// ObjA.qml
Item {
id: objA
Component {
id: cm
ObjB {}
}
function create() { cm.createObject(objA) }
}
// ObjB.qml
Item {
Component.onCompleted: console.log(objA)
}
// main.qml
Component {
id: cm
Rect {}
}
Obj {
anchors.fill: parent
MouseArea {
anchors.fill: parent
acceptedButtons: Qt.LeftButton | Qt.RightButton
onClicked: {
if (mouse.button === Qt.LeftButton) {
cm.createObject(parent)
} else {
parent.create()
}
}
}
}
As this practical example illustrates, even though in both cases the newly created object is parented to the same object that has the objA identifier, the object created in main.qml cannot resolve it, because it is created in a context where objA is still not defined, but it works if the object is created in the context of objA, and it will work even if it is burred even higher up the tree.
To put it in a more generic way, an id becomes visible in the context of the source's root object and remains visible in every subsequent sub-context until it is shadowed by an identically named object. Visibility cannot reach down the tree to contexts that exist before the context the id is defined in.
Note the subtle difference - a_item refers to an Item whereas a1 refers to an a. And since a1 is visible inside a.qml it will always refer to that one instance of a that is in main.qml, regardless of which instance of a you might be in, whereas a_item will refer to a different object for each different instance of a. a_item is "relative" and will be different in every different instance of a but a1 is absolute and will always refer to a specific instance of a. This is the case because a1 is a concrete instance whereas a_item is a type / prototype.
// Obj.qml
Item {
id: obj
Component.onCompleted: console.log(obj === oid)
}
// main.qml
Obj { } // false
Obj { id: oid } // true
Dynamic scoping of ids can be quite useful and cut the time it takes to implement a workaround to get access to the stuff you need. Which is also why it is a very good idea to give the id descriptive names rather than just main.
For example, if you have a manager that manages a number of views, each with a number of objects in them, you can quickly get access the respective view for each object and also get access to the manager without having to implement any additional stuff. The rule of thumb is that the manager must come first, then each view should be created in the context of the manager, not necessarily directly in it, but in it nonetheless, and each object should be created in the context of a view. And of course take care not to shadow over things. If you break that rule things will not resolve properly.
View.qml { id: view }
manager
view1
object // view is view1
view2
object // view is view2
view3
object // view is view3
Naturally, this makes sense only in specific purpose designs where you know what the general structure of the context tree is gonna be like. If you are making generic elements that may go just about anywhere, you should absolutely not be relying on accessing ids across sources, and you should implement a more generic usage interface via properties, aliases and whatnot.

Double-Initialisation of values in QML

I have a strange problem, that is burried somewhere within a large project. So far I was not able to reproduce it in a MCVE, but as soon as I succeed, I will turn it in.
It is quite a simple missbehavior. Basically I have an QtObject with properties, that I set with initial values as such:
TestObj.qml
QtObject {
id: root
property int val1: { console.log('set val', root); return 42 }
Component.onCompleted: console.log('Constructed Object', this)
}
!!! With this example, I do not reproduce the error !!!
The output in my project would be now:
set val TestObj_QMLTYPE_44(0x33799fa8)
set val TestObj_QMLTYPE_44(0x33799fa8)
Constructed Object TestObj_QMLTYPE_44(0x33799fa8)
So, though the object is only created once, the initial property assignment is performed twice.
As I have no idea, where to look for the culprit, I can't produce a reproducable example, but maybe someone stumbled uppon the same situation already and found a solution.
A solution would be beneficial, as this issue results in multiple instantiations of some objects, that I can not destroy.
Created Bug-Report: maybe they find a way to solve this issue withouth hacky workarounds
The problem are circular references:
Circular references are resulting in a strange behavior when creating objects.
TestObj1.qml
import QtQuick 2.0
QtObject {
property Item paps
property int myVal: { console.log('myVal'); paps.val }
}
TestObj2.qml
import QtQuick 2.0
Item {
id: root
property int val: { console.log('set val', root); return 42 }
Component.onCompleted: console.log('Constructed Object')
TestObj1 {
id: to1
paps: root
}
}
Result:
qml: myVal
qml: set val TestObj_QMLTYPE_4(0x2c0bafb0)
qml: set val TestObj_QMLTYPE_4(0x2c0bafb0)
qml: Constructed Object
The probalbe cause for this is, that the statement {console.log('set val', root); return 42 } has not been processed, when it is allready assigned to myVal, therefore that statement is executed twice.
While this is no problem in normal situations, it might lead to problems, as long as we don't have dynamically created objects in those properties.
TestObj3.qml
import QtQuick 2.0
Item {
id: root
property QtObject obj: { console.log('set obj'); return objPrototype.createObject(root) }
Component.onCompleted: console.log('Constructed Object', obj)
TestObj4 {
id: to1
paps: root
}
Component {
id: objPrototype
QtObject {
id: op
Component.onCompleted: console.log('PropertyObject created', op)
}
}
}
TestObj4.qml
import QtQuick 2.0
QtObject {
property Item paps
property QtObject myObj: paps.obj
Component.onCompleted: console.log(myObj)
}
Result:
qml: set obj
qml: PropertyObject created QObject(0x2c124708)
qml: set obj
qml: PropertyObject created QObject(0x2c1246f8)
qml: Constructed Object QObject(0x2c1246f8)
qml: QObject(0x2c1246f8)
So you can see, the object is indeed created twice.
There are some workarounds:
Don't use circular references - but that would be booring.
Don't use dynamic object creation, as it always produces problems - I could just create the object, and either use property alias obj: myObjectID or property QtObject obj: myObjectID. This has the downside, that if the component is reusable, that the user can't replace that object or the object is still created, wasting memory.
Assign the property in Component.onCompleted if the property is still empty (not overwritten by the user of the reusable component). This has the downside, that the object is not available, uppon creation and a lot of Can't read property ... of null errors will appear. They will hopefully don't break the app though.
Create a nasty binding loop Write: property QtObject obj: (obj ? obj : objPrototype.createObject(root)). It will throw a warning, but c'mon. It's just a binding loop, that will be detected and broken.
Nothing nice in those workarounds, but maybe something usable.

QML dictionary (jsobject, var) sub-properties notify

Is it possible to raise notify-method of a var/variant/object/ (etc.) variables automatically during updating?
Suppose I have:
property var objects: {'obj1': 'unnamed', 'obj2': 'unnamed'}
Next I have binding in, for example, text:
Text {
text: objects.obj1
onTextChanged: objects.obj1 = text
}
In onTextChanged I want to raise a notify signal of objects variable to update it everywhere.
Hm, if I am not mistaken, QML generates a onObjectsChanged signal handler for objects but it is not emitted when you change objects internally, and due to QML brilliant design, you cannot emit objectsChanged() manually, it is expected to automatically emit, except that it doesn't. It only emits when the property is reassigned to another object.
You cannot create a signal for the JS object, since that requires a QObject derived class to get signals and therefore notifications and bindings.
You can force to emit objectsChanged() by reassigning the objects property a new object with the new value for obj1 and the old value of obj2, this will force the second text element to update and show the new value. It is not exactly elegant, but if you really need to use the JS object, it is a valid solution. Otherwise you will have to use a QtObject element and QML properties for obj1/2
property var objects: {'obj1': 'unnamed', 'obj2': 'unnamed'}
Column {
spacing: 30
TextEdit {
text: objects.obj1
onTextChanged: {
objects = {'obj1': text, 'obj2': objects.obj2}
}
}
Text {
text: objects.obj1
}
}
Another possible solution would be to simply not rely on notifications from objects and use a proxy property as a controller for it.
property var objects: {'obj1': 'unnamed', 'obj2': 'unnamed'}
property string obj1: objects.obj1
onObj1Changed: objects.obj1 = obj1
This way you don't use objects at all, except for storing data into it, use the obj1 property instead, and every time it is changed it will write the changed into objects without reassigning the entire objects as in the first solution.
But unless you really need the JS objects, I'd recommend scrapping it and using a more QML friendly data representation..

Problem with Adding multiple child objects to an existing entity in EF

I need to add multiple child objects to an existing parent Object. I am instantiating my parent object and sets it Key/Id in my UI processing layer(to which my child objects will be added).
Parent parenttoModify = new Parent();
parenttoModify.Parent_Id = 5; //this comes from some Index of a dropdown or a key column of a grid, i Have put a dummy value here for example
parenttoModify.Children.Add(child);
parenttoModify.Children.Add(child2);
DataAccess.ModifyParent(parenttoModify);
In my data access layer I have a method like :
public static bool ModifyParent(Parent parent)
{
int recordsAffected=0;
using (TestEntities testContext = new TestEntities())
{
testContext.Parents.Attach(parent);
var parentEntry = testContext.ObjectStateManager.GetObjectStateEntry(parent);
parentEntry.ChangeState(System.Data.EntityState.Modified);
recordsAffected = testContext.SaveChanges();
}
return recordsAffected > 0 ? true : false;
}
I get an error when testContext.Parent.Attach(parent) is called. It says:
Object with same key already exist.
I am not sure why is this happening since i am not adding a parent object, I am just attaching it and adding child objects within it.
Any idea where I am going wrong?
Where do you add childs? I guess you are not showing all code. When you call Attach or AddObject EF always attaches or adds all entities from object graph which are not known (tracked) to context at the moment. The exception says that some entity - probably parent - is already tracked by the context. So you have either:
Used shared context (you are creating a new instance in ModifyParent so it should not be a case)
Load parent from the context first in ModifyParent
Called Attach or AddObject on any child before attaching parent.
All these operations lead to the exception you are receiving.

Resources