Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-119545

Document that the URL passed to Qt.createQmlObject() can make it override existing components

    XMLWordPrintable

Details

    Description

      It seems that it is impossible to dynamically create an instance of an inline component from the same file.

      Simple test code (file called Main.qml):

      import QtQuick 2.0
      import QtQuick.Controls 2.0
      import QtQuick.Window 2.0
      Window {
        id: root
        Button {
          anchors.bottom: parent.bottom
          text: "Create dynamic"
          onClicked: {
            var obj = Qt.createQmlObject("CustomRect {}", root, Qt.resolvedUrl("Main.qml"))
            console.log("dynamic object:", obj)
          }
        }
        component CustomRect: Rectangle {
          width: 200;
          height: 60;
          color: "orange"
        }
      }
      

      This gives the error message: Main.qml:1:1: CustomRect is not a type

      The documentation states that inline components can be "imported" via the QML file name.

      But if changing the code to

      var obj = Qt.createQmlObject("Main.CustomRect {}", root, Qt.resolvedUrl("Main.qml")) 

      The error message is: Main.qml:1:1: Main.CustomRect - Main is neither a type nor a namespace

      However: it is possible to use an inline component of a different QML file. The following code works as expected:

      var obj = Qt.createQmlObject("MainFile.CustomRect2 {}", root, Qt.resolvedUrl("Main.qml"))

      Where MainFile.qml defines another inline component called CustomRect2.

      And it also works when changing the context URL:

      var obj = Qt.createQmlObject("Main.CustomRect {}", root, Qt.resolvedUrl("NonExistentFile.qml"))

      However then the new QML object has its context set to NonExistentFile.qml which is not ideal for error handling etc.

      The exact same behavior is true when trying to create an instance from C++ via QQmlComponent.

      It seems that the Main is neither a type nor a namespace is a bug, or that when using the exact URL of the QML file that contains the inline component, the component should be available without "import".

      Tested and observed with Qt 5.15.2, 6.4.1, 6.6.1.

      Attachments

        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

        Activity

          People

            qtqmlteam Qt Qml Team User
            Chrisu Christian Bartsch
            Votes:
            6 Vote for this issue
            Watchers:
            6 Start watching this issue

            Dates

              Created:
              Updated:

              Gerrit Reviews

                There are no open Gerrit changes