2017-06-16 31 views
1

改變組件一項的QML文件,代碼,如:如何訪問和QML

StackView { 
    id: stackView 
    anchors.right: parent.right 
    width: parent.width/2-20 
    initialItem:patientdetail 

    Component{ 
     id:patientdetail 
     Column { 
      id:detailcolumn 
      spacing: 2 
      anchors.right: parent.right 
      width: parent.width/2-20 

      Label { 
       id: label 
       color: "#ffffff" 
       text: qsTr("User ID") 
      } 

      TextField { 
       id: textField_id 
       readOnly: true 
       placeholderText: qsTr("") 
      } 
     } 
     } 
    Component{ 
     id:component2 
     //...other component will add to stackview 
     } 
    } 

而且我想改變文本字段的一個JS函數的文本(在同一個文件),如:

function updatedetail(clear,rowindex){ 
    if(clear){ 
     textField_id.text=""; 
    } 
    else{ 
     textField_id.text=jsonModel1.model.get(rowindex).id; 
    } 
} 

但有一個錯誤:

ReferenceError: textField_id is not defined

發生錯誤

? 0

回答

2

當您試圖更改尚未實例化的對象時,它將失敗。但即使它被實例化,它的id也將處於不同的範圍,這是不可能達到的。
這是必要的,因爲可能多次實例化相同的Component(例如作爲ListView中的delegate),所以它在上下文中不再是唯一的。

Uppon實例化您的StackView,您的Component將被實例化並推送到StackView。現在你有一個實例,可能會改變使用的公開屬性:

currentItem.textFieldText = newValue 

在你的函數中。對於這個工作,你需要公開的財產:

Component{ 
    id:patientdetail 
    Column { 
     id:detailcolumn 
     spacing: 2 
     anchors.right: parent.right 
     width: parent.width/2-20 

     property alias textFieldText: textField_id.text // in this context, you have access to the id. Expose it, to change it from the outside. 

     Label { 
      id: label 
      color: "#ffffff" 
      text: qsTr("User ID") 
     } 

     TextField { 
      id: textField_id 
      readOnly: true 
      placeholderText: qsTr("") 
     } 
    } 
} 

然而,作爲實例可能被破壞,後來重建,這種變化不會是永久性的,所以這將是更好地TextField.text綁定的屬性一個物體,只要有必要就會存活下去。這可以是從C++公開的contextProperty或作爲模型傳遞的QtObject,或者僅僅是屬性,例如,在StackView

StackView { 
    id: stackView 
    anchors.right: parent.right 
    width: parent.width/2-20 
    initialItem:patientdetail 

    // Change this property. The textField_id.text will be bound to it. 
    property string textFieldText 

    Component{ 
     id:patientdetail 
     Column { 
      id:detailcolumn 
      spacing: 2 
      anchors.right: parent.right 
      width: parent.width/2-20 

      Label { 
       id: label 
       color: "#ffffff" 
       text: qsTr("User ID") 
      } 

      TextField { 
       id: textField_id 
       readOnly: true 
       placeholderText: qsTr("") 
       text: stackView.textFieldText 
      } 
     } 
    } 
} 
+0

理解,謝謝你的回答。我怎樣才能定義一些不顯示在q Qml文件中的項目(或元素),這些項目會在我想要的時候顯示在stackview或swipview中。 –

+1

嗯,我接受了。但我無法贊成,也許我沒有足夠的聲望。:( –