Reputation: 9832
How can I conditionally set different properties of a property group in one go?
Example: Let's say that there is a context property _context.condition
available. Given that value I would like to set different anchors for a qml item.
// Some item...
Rectangle {
id: square
width: 50
height: 50
// For simple properties this should work:
color: { if (_context.condition) "blue"; else "red" }
// But how to do it for complex properties like 'anchors'?
// Note that I set different properties for different values of the condition.
// Here is how I would do it, but this does not work:
anchors: {
if (_context.condition) {
// Anchors set 1:
horizontalCenter: parent.horizontalCenter
bottom: parent.bottom
bottomMargin: 20
} else {
// Anchors set 2:
verticalCenter: parent.verticalCenter
right: parent.right
rightMargin: 20
}
}
}
I'm using QtQuick 2.0 in Qt 5.3. Thanks!
Upvotes: 11
Views: 8932
Reputation: 2102
You can try this (not tested):
anchors {
horizontalCenter: _context.condition ? parent.horizontalCenter : undefined;
bottom: _context.condition ? parent.bottom : undefined;
bottomMargin: _context.condition ? 20 : undefined;
verticalCenter: _context.condition ? undefined : parent.verticalCenter;
right: _context.condition ? undefined : parent.right;
rightMargin: _context.condition ? undefined : 20;
}
Also, according this empty curly braces can be used to reset the value of property:
Item {
property var first: {} // nothing = undefined
property var second: {{}} // empty expression block = undefined
property var third: ({}) // empty object
}
Upvotes: 13
Reputation: 11096
In addition to the Max Go answer, I've found that null
is sometimes required instead of {}
, etc. Some QML properties resolve to C++ pointers under the hood, and null can equate "default" in such cases.
Upvotes: 0