qmlqtquick-designer

Using behavior in qml ui form


is there a way to use behavior from outside the item ? (QtQuick designer doesn't support behavior).

say I have a rectangle defined in From.ui.qml with then id rec, in the file Form.qml I want to assign a behavior on x property of rec, how can I do it.?


Solution

    1. Step: Expose the object with the property you want to change

    enter image description here

    This will create a property alias in the ui.qml-file.

    // NewFormular.ui.qml

    import QtQuick 2.4
    
    Item {
        width: 400
        height: 400
        property alias rectangle1: rectangle1
    
        Rectangle {
            id: rectangle1
            x: 77
            y: 69
            width: 200
            height: 200
            color: "#ffffff"
        }
    }
    
    1. Step: Add the Behavior

    //New.qml

    import QtQuick 2.4
    
    NewFormular {
        Behavior on rectangle1.x {
            NumberAnimation { duration: 500 }
        }
    
        Timer {
            running: true
            interval: 1000
            repeat: true
            onTriggered: rectangle1.x = (rectangle1.x + 500) % 600
        }
    }
    
    1. Step: Instantiate it in your main.qml

    //main.qml

    import QtQuick 2.7
    import QtQuick.Controls 2.0
    
    ApplicationWindow {
        id: window
        width: 800
        height: 600
        visible: true
        color: 'grey'
        New {
            anchors.fill: parent
        }
    }
    

    If you want to hide it again, you can wrap it in a Item again:

    //New.qml v2

    import QtQuick 2.4
    Item {
        id: root
        NewFormular {
            anchors.fill: parent
            Behavior on rectangle1.x {
                NumberAnimation { duration: 500 }
            }
    
            Timer {
                running: true
                interval: 1000
                repeat: true
                onTriggered: rectangle1.x = (rectangle1.x + 500) % 600
            }
        }
    }