开发者

Navigating and addressing QMLComponents

开发者 https://www.devze.com 2023-02-22 21:58 出处:网络
I am working on a desktop application the uses a QML开发者_运维技巧 GUI with a lot of QML Components.

I am working on a desktop application the uses a QML开发者_运维技巧 GUI with a lot of QML Components. These are parts of the hierarchy:

main -> toolbar -> searchbar -> editfield

and

main -> resultlist -> header -> button1

I could not find a way to access the text contents of editfield in a signal handler for button1. Is it possible to do that in QML or Javascript?

I know I can access the element in the C++ part by using the objectName property.


Due to QML uses dynamic scoping (→ Doc), child elements can access the properties of all ancestors and it doesn't matter if they are in different files.

So you could add an editFieldText property to main and bind the text property of editfield to it. Then you can access editFieldText from everywhere:

//=== main.qml ===
import QtQuick 1.0

Rectangle {
    id: main

    property string editFieldText

    Toolbar {
        // [...]
    }

    Resultlist {
        // [...]
    }
}


//=== EditField.qml ===
import QtQuick 1.0

TextInput {
    // bind text property to main.editFieldText
    Binding {
        target: main;
        property: "editFieldText";
        value: text
    }
}


//=== Header.qml ===
import QtQuick 1.0

Rectangle {
    Button {
        onClick: {
            console.log(main.editFieldText);
            // or simply
            console.log(editFieldText);
        }
    }
}


You can use alias properties to have the editfield.text as a property of main. This property should be accessible from button1.

0

精彩评论

暂无评论...
验证码 换一张
取 消