Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QML: Conditionally set different properties of a property group

Tags:

qt

qml

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!

like image 612
normanius Avatar asked Oct 02 '14 15:10

normanius


Video Answer


1 Answers

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;
        }

Resetting properties values

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
}
like image 175
Max Go Avatar answered Sep 19 '22 15:09

Max Go