Qt Quick using delegate and call 'parent'
-
ListView { id: cowListView width: parent.width Layout.alignment: Qt.AlignHCenter | Qt.AlignVCenter model: _ResourceVec.getSize() delegate: ItemDelegate { width: parent.width anchors.horizontalCenter: parent.horizontalCenter
When i use delegate in list view and then call parent in it, this error occur.
TypeError: Cannot read property 'width' of null TypeError: Cannot read property 'horizontalCenter' of null
it seems like have problem getting 'parent '.
But somehow my code works perfectly as i intended
I'm ignoring that error but i know why it happens and what is the perfect solution.i use QT 5.14.2 and used library is
import QtQuick 2.12 import QtQuick.Layouts 1.14 import QtQuick.Controls 2.12
-
Instances of the delegate aren't direct children of the view. The implementation looks something like this:
ListView |-ListView contentItem |-delegate instance 0 |-delegate instance 1 | ... |-delegate count - 2 |-delegate count - 1
To have a delegate instance refer to the properties of the ListView, either reference it by id:
delegate: ItemDelegate { width: cowListView.width }
or use the attached properties:
delegate: ItemDelegate { width: ListView.view.width # ListView.view == cowListView }
Using attached properties is advantageous for portability. Renaming cowListView won't break its delegate. On the other hand, the attached properties are only attached to the top level delegate. Descendents of the delegate generally need to explicitly reference the top of the delegate tree in some form.