我們有一個ApplicationWindow基礎main.qml,它通過 QmlElement 連接到我們的 python 后端Bridge。我們有一個視圖Slot-methods,它直接將值回傳到 qml 前端以更改文本欄位,這些文本欄位是ApplicationWindow以下內容的子欄位:
ApplicationWindow {
id: mainFrame
width: 1280
height: 720
visible: true
title: qsTr("Test")
StackView {
id: stack
initialItem: loginFrame
anchors.fill: parent
}
Bridge {
id: bridge
}
Component{
id: loginFrame
ColumnLayout {
anchors.margins: 3
spacing: 3
Layout.columnSpan: 1
Layout.alignment: Qt.AlignHCenter
Text {
id: title
Layout.alignment: Qt.AlignHCenter
font.pointSize: 16
text: "Login Screen"
Layout.preferredHeight: 100
}
Button {
id: loginButton
Layout.alignment: Qt.AlignHCenter
text: "login"
highlighted: true
Material.accent: Material.Red
onClicked: {
title.text = bridge.login(username.text, password.text)
}
}
}
}
}
為了減小我們的大小,main.qml我們決定從不同的檔案中加載其他布局、組件等
Loader {
id: otherLoader
source: "other.qml"
}
由于值由 ? 提供,如何訪問Text內部的 Objectother.qml以更新text屬性?main.qmlBridge
我已經嘗試過從另一個 QML 檔案訪問 TextField,但這沒有奏效。
uj5u.com熱心網友回復:
在Loader與靜態創建專案使用的背景關系不同的背景關系中創建專案,因此無法訪問加載的專案。您有幾種方法可以訪問此類專案。
第一種也是最正確的方法是使用宣告式風格:
Item {
id: container
anchors.fill: parent
property string someText: "press again"
Loader {
id: loader
active: false
sourceComponent: Text {
id: txt
text: container.someText
}
}
MouseArea {
anchors.fill: parent
onClicked: {
if(loader.active)
container.someText = "some text"
else
loader.active = true
}
}
}
Javascript您可以隨時在代碼中創建系結:
Loader {
id: loader
active: false
sourceComponent: Text {
id: txt
Component.onCompleted: {
txt.text = Qt.binding(function() { return container.someText; })
}
}
}
另一種選擇是使用Loader.item屬性:
Item {
id: container
anchors.fill: parent
property string someText: "some text"
Loader {
id: loader
active: false
sourceComponent: Text {
id: txt
text: "press again"
}
}
MouseArea {
anchors.fill: parent
onClicked: {
if(loader.active)
loader.item.text = "some text"
else
loader.active = true
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/514833.html
