0

My code:

import QtQuick 2.6
import QtQuick.Window 2.2

Window {
    visible: true
    width: 640
    height: 480

    Item {
        id: loaderParent
        Loader {
            id: loader
            active: true
            sourceComponent: Item {
                parent: loaderParent
                x: parent.x
            }
        }
    }

    Item {
        focus: true
        Keys.onPressed: {
            loader.active = false;
        }
    }
}

When I press any key, I get this error:

qrc:/main.qml:16: TypeError: Cannot read property of null

Thought I suspect this error is harmless, I'd like an explanation or any idea for a fix/workaround?

Reported here.

Stefan Monov
  • 11,332
  • 10
  • 63
  • 120

2 Answers2

0

I found a workaround: instead of fetching parent.x, fetch loaderParent.x. Still want to know why the problem happens.

Stefan Monov
  • 11,332
  • 10
  • 63
  • 120
0

The Loader appears to set the item parent to null on destruction. QML objects are not deleted immediately, instead they use deleteLater() which leaves the object alive for another event loop cycle.

This leads to a reevaluation of the binding expression, which is no longer possible since the parent is now null. I've had a more severe encounter with this behavior described here.

A simple way to avoid it would be to not use the parent property which you already found, or to use a more complex binding expression such as x: loader.active ? parent.x : someFailsafeValue.

By using onParentChanged: console.log(parent) you can verify that the parent indeed changes to null when the loader is deactivated.

dtech
  • 47,916
  • 17
  • 112
  • 190
  • I left a comment on the other answer as well, but just for those who might only see this one, here are some relevant bug reports: https://bugreports.qt.io/browse/QTBUG-60344, https://bugreports.qt.io/browse/QTBUG-51995. – Mitch Jul 07 '17 at 20:23