Parent is null in ListView delegate after upgrade to Qt 5.15

前端 未结 1 851
青春惊慌失措
青春惊慌失措 2021-01-13 17:15

A ListView with a most simple delegate produces lots of warnings "21:35:31.911 warning T#16084047 unknown - qrc:/main.qml:15: TypeError: Cannot read

相关标签:
1条回答
  • 2021-01-13 18:03

    This is the result of a behaviour change in Qt 5.15. The first issue was reported here, with a more detailed summary here. The documentation was updated but may take a little longer to make it onto the website. The new documentation says:

    Delegates are instantiated as needed and may be destroyed at any time. As such, state should never be stored in a delegate. Delegates are usually parented to ListView's contentItem, but typically depending on whether it's visible in the view or not, the parent can change, and sometimes be null. Because of that, binding to the parent's properties from within the delegate is not recommended. If you want the delegate to fill out the width of the ListView, consider using one of the following approaches instead:

    ListView {
        id: listView
        // ...
    
        delegate: Item {
            // Incorrect.
            width: parent.width
    
            // Correct.
            width: listView.width
            width: ListView.view.width
            // ...
        }
    }
    

    So, you can either:

    1. Give the ListView an id and use it in the binding instead of parent.
    2. Use the attached property (ListView.view) to access the view.
    3. Check for null (anchors.left: parent ? parent.left : undefined).

    Options 1 and 2 will result in cleaner code.

    Option 1 results in one less QObject being created (each attached object is a QObject) but ties the delegate to that particular view.

    Option 2 is better for delegates that are standalone components that will be reused with other ListViews.

    0 讨论(0)
提交回复
热议问题