2017-07-29 821 views
0

[編輯]:我想刪除它在列QML 型動態創建以及如何訪問一個佈局的孩子一些控制? 。繼是代碼這不是動態的,僅供參考:如何從列QML元素中刪除動態創建的項目

import QtQuick 2.6 
import QtQuick.controls 2.2 

Item 
{ 
Column { 
    id:col 
    spacing: 2 

    //Initially Adding controls. 
    Rectangle { color: "red"; width: 50; height: 50 } 
    Rectangle { color: "green"; width: 20; height: 50 } 
    Rectangle { color: "blue"; width: 50; height: 20 } 
} 

Button 
{ 
    id:button 
    onClicked: 
    { 
     //How to remove a perticular element from above column which is created dynamically? 
    } 

} 

    // [EDIT] - Code to add controls dynamically to column. 
} 
+1

可能的複製[刪除QML Grid的子項](https://stackoverflow.com/questions/8851164/delete-children-of-qml-grid) – m7913d

+2

我通常會建議採用數據驅動的方法('Repe ater「等),而不是手動構建和銷燬元素。 – peppe

+0

@ m7913d你不應該依賴垃圾收集器。只有當你使用'component.createObject(null)'時,它纔會起作用,然後隨着時間的推移它會緩解地破壞你的對象,很可能在你想要它消失之前,因爲引用計數被破壞了。如果它運行很少,那麼應用程序一運行就會崩潰。如果你使用'component.createObject(someParent)',它根本無法工作。然後它是你的責任,用'instance.destroy()'銷燬它。由於上述原因,這是處理來自JS的動態實例化的唯一合理方式。 – derM

回答

1

//如何從上述柱除去perticular元件?

使用下面提到代碼[參考:https://stackoverflow.com/a/8852535/3459185]

col.children[index_to_destroy].destroy() 

[編輯]樣本代碼在列動態地添加和刪除要素:

Item 
{ 
    ListModel { 
     id: elementModel 
     ListElement { elementColor: "red"; elementWidth: 50; elementHeight: 50} 
     ListElement { elementColor: "green"; elementWidth: 20; elementHeight: 50} 
     ListElement { elementColor: "blue"; elementWidth: 50; elementHeight: 20} 
    } 

    Column { 
     id:col 
     spacing: 2 
     Repeater { 
      model: elementModel 
      Rectangle { color: elementColor; width: elementWidth; height: elementHeight } 
     } 
    } 

    Button 
    { 
     id: deleteButton; x: 200; y: 200; height: 50; width: 50; text: "Delete" 
     onClicked: 
     { 
      //How to remove perticular element from above column ? 
      elementModel.remove(index) 
     } 
    } 

    Button 
    { 
     id: addButton; x: 400; y: 200; height: 50; width: 50; text: "Add" 
     onClicked: 
     { 
      // Code to add controls dynamically to column. 
      elementModel.insert(index, { "elementColor": "red", "elementWidth": 50, "elementHeight": 50}) 
     } 

    } 
} 
+0

@ m7913d - 對於「不允許」的東西,它似乎工作得很好,你 – dtech

+0

@dtech如果你不遵循文檔,它可能(看起來)現在工作,但沒有保證它會在未來。 (請注意[Atron的回答](https://stackoverflow.com/a/32047782/7621674)現在是不相關的,因爲OP已經指定他使用動態創建的對象。) – m7913d

+1

我工作的項目廣泛地依賴於修改和甚至刪除通過聲明代碼實例化的對象,並且完成了大量的測試,沒有明顯的問題。文檔也有可能是錯誤的,或者可能針對特定情況而不提及它們。請記住,文檔不是「絕對的神聖真理」,它只是像其他代碼一樣受到bug的影響。事實上,Qt 5文檔在5.4版左右的版本中是非常糟糕的。 – dtech