2016-11-16 4 views
0

Я хочу выровнять свой список телефонных номеров с одним полем («имя») с левой стороны и другим полем («телефон») с правой стороны. Однако при попытке связать свойства привязки внутри делегата, он говорит, что объект делегата не является родительским элементом компонента ListView. Как мне добраться до других компонентов от делегата?Как выровнять компоненты QML в делегате

Это мой QML код:

import QtQuick 2.7 
import QtQuick.Controls 2.0 

Item { 
    id: enclosing_area 
    width: 500 
    height: 300 
    ListModel { 
     id: dataModel 
     ListElement { 
      name: "John Smith" 
      phone: "1111-1111" 
     } 
     ListElement { 
      name: "Peter Poter" 
      phone: "2222-2222" 
     } 
     ListElement { 
      name: "Anna Lasalle" 
      phone: "3333-3333" 
     } 
    } 

    ListView { 
     id: list 
     width: enclosing_area.width 
     height: enclosing_area.height 
     model: dataModel 
     delegate: Rectangle { 
      width: enclosing_area.width 
      border.color: "red" 
      Label { 
       text: name 
       anchors.left: list.left 
      } 
      Label { 
       text: phone 
       anchors.right: list.right 
      } 
     } 
    } 
} 

qmlscene производит следующие ошибки:

file:///LViewTest.qml:36:13: QML Label: Cannot anchor to an item that isn't a parent or sibling. 
file:///LViewTest.qml:32:13: QML Label: Cannot anchor to an item that isn't a parent or sibling. 
file:///LViewTest.qml:36:13: QML Label: Cannot anchor to an item that isn't a parent or sibling. 
file:///LViewTest.qml:32:13: QML Label: Cannot anchor to an item that isn't a parent or sibling. 
file:///LViewTest.qml:36:13: QML Label: Cannot anchor to an item that isn't a parent or sibling. 
file:///LViewTest.qml:32:13: QML Label: Cannot anchor to an item that isn't a parent or sibling. 

Линии 32 и 32 "anchors.left" и "anchors.right" заявления. Как мне привязать к свойствам в других объектах из делегата в моем случае?

ответ

3

В первый:

Было бы условность назвать свой enclosing_arearoot вместо этого.
Во-вторых, если вы не привязываетесь к брату, не используйте id объекта, к которому вы хотите привязать, но используйте parent.

Это предотвращает вас от ваших ошибок, так как - то, что вы пытаетесь сделать - не анкеровки к родителю из Label с, но их parent s parent.
parentLabel будет Rectangle в вашем delegate.

ListView { 
    id: list // <- This is not the parent of the Labels, but of the delegateRectangle 
    width: enclosing_area.width  // works 
    height: enclosing_area.height // works 
    // anchors.fill: parent   <- would do the same, more flexible, and only one line. 
    model: dataModel 
    delegate: Rectangle { 
     id: delegateRectangle // <--- This is the parent of the two Labels 
     width: enclosing_area.width 
     height: 30 // <- a heightis necessary. 
        // As the objects are repositioned you need to set it explicitely 
        // and can't use anchoring. You could use the 
        // implicit height of it's children, to make it nice 
     border.color: "red" 
     Label { 
      text: name 
      anchors.left: delegateRectangle.left // this would work instead. 
               // list.left woudl try to anchor to the 'grandparent' 
     } 
     Label { 
      text: phone 
      anchors.right: parent.right // this would be the reccomended way. 
             // Would also anchor to delegateRectangle 
     } 
    } 
} 

Почему вы должны предпочесть якорь к parent, а не ваш parent s id?
Объект будет (почти) всегда иметь визуальный родительский элемент, но этот визуальный родитель может измениться. Либо потому, что вы добавляете дополнительный слой в код, позже - или даже во время выполнения, путем его повторного заполнения. Поэтому вам всегда нужно обновлять якоря.
Таким образом, привязка к parent разрешает одну легкую ошибку.

1

Воспользуйтесь якорями вместо того, чтобы пытаться жестко задавать размер дочернего элемента в соответствии с его родительским. Это позволит вам использовать якоря до конца. (Аналогично, используйте привязные поля вместо жестко заданных значений x, y). Вы получаете много других преимуществ с якорями.

ListView { 
     id: list 
     anchors.fill: parent 
     model: dataModel 
     delegate: Rectangle { 
      anchors.left: parent.left 
      anchors.right: parent.right 
      height: 50  // you need a height otherwise all rows are on the same line 
      border.color: "red" 
      Label { 
       text: name 
       anchors.left: parent.left 
      } 
      Label { 
       text: phone 
       anchors.right: parent.right 
      } 
     } 
    } 
} 
Смежные вопросы