QML:有条件地设置属性组的不同属性

nor*_*ius 7 qt qml

如何有条件地一次性设置属性组的不同属性?

示例:假设有一个_context.condition可用的上下文属性.鉴于该值,我想为qml项设置不同的锚点.

// 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在Qt 5.3中使用QtQuick 2.0.谢谢!

Max*_* Go 9

你可以尝试这个(未测试):

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;
        }
Run Code Online (Sandbox Code Playgroud)

重置属性值

另外,根据这个空花括号可以用来重置属性的值:

Item {
    property var first:  {}   // nothing = undefined
    property var second: {{}} // empty expression block = undefined
    property var third:  ({}) // empty object
}
Run Code Online (Sandbox Code Playgroud)