Details
-
Bug
-
Resolution: Fixed
-
P2: Important
-
5.15.2, 6.4.1, 6.6.1
-
None
-
d278c2338 (dev), 24e7e04a1 (6.9), b160a20ec (6.8), bfdd23aba (tqtc/lts-6.5)
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
For Gerrit Dashboard: QTBUG-119545 | ||||||
---|---|---|---|---|---|---|
# | Subject | Branch | Project | Status | CR | V |
625433,3 | Doc: Warn about shadowing URLs when dynamically creating components | dev | qt/qtdeclarative | Status: MERGED | +2 | 0 |
625831,2 | Doc: Warn about shadowing URLs when dynamically creating components | 6.9 | qt/qtdeclarative | Status: MERGED | +2 | 0 |
625910,2 | Doc: Warn about shadowing URLs when dynamically creating components | 6.8 | qt/qtdeclarative | Status: MERGED | +2 | 0 |
625940,2 | Doc: Warn about shadowing URLs when dynamically creating components | tqtc/lts-6.5 | qt/tqtc-qtdeclarative | Status: MERGED | +2 | 0 |