Why does QQmlComponent::create() return null?
-
Under what conditions does QQmlComponent::create(QQmlContext *) fail by returning nullptr? The documentation only says " Returns nullptr if creation failed" without further detail. My backend C++ code tries to instantiate a MessageDialog from the following .qml:
import QtQuick 2.0 import QtQuick.Dialogs 1.1 MessageDialog { id: messageDialog title: "My message" text: "Fill in this message from C++" onAccepted: { console.log("Knew you'd see it my way!") // Hide the dialog visible = false } Component.onCompleted: visible = true }
And here's a fragment of my backend constructor:
QQmlApplicationEngine engine; // Note that resource URL is a local file, not network, // no need to wait before calling create()? QQmlComponent *component = new QQmlComponent(&engine, QStringLiteral("ui-components/MessageDialog.qml")); // Following call returns nullptr - why??? QObject *childItem = component->create();
Anyone know why? Thanks!
-
@Tom-asso said in Why does QQmlComponent::create() return null?:
QStringLiteral("ui-components/MessageDialog.qml"));
You're using a relative path: are you sure the QML file is actually found?
Also, before calling create() - did you check https://doc.qt.io/qt-5/qqmlcomponent.html#isError and https://doc.qt.io/qt-5/qqmlcomponent.html#isNull ?
-
@Tom-asso said in Why does QQmlComponent::create() return null?:
Anyone know why?
-
@jsulm said in Why does QQmlComponent::create() return null?:
It was a relative path problem - thank you!
My application did not print out any Qt-level messages to stderr when create() failed - it was silent and mysterious. ;-) Is there any way to make Qt more verbose? For example if it had printed out "QML file not found" that would have saved me hours of trouble!Thanks
Tom -
@Tom-asso said in Why does QQmlComponent::create() return null?:
Is there any way to make Qt more verbose?
I don't know if there is an automatic way, but you might start using asserts to check for null and other conditions. The asserts will only translate to code when in debug mode, in release they will disappear.
Q_ASSERT_X(component != nullptr, "createComponentFunction", QQmlComponent::errors()[0].toString()); // might need a lambda to get all errors in list or Q_ASSERT(component != nullptr);
-
@Tom-asso It's what @raven-worx suggested above...
-
Just to add to this.
I was having QQmlComponent::create() failing too, and it wasn't any problem with the paths.
It turned out to be the root type use to instantiate the component was an ApplicationWindow.
I'm not sure if this was clashing with my main QApplicationMainWindow class that I had elsewhere..?
Anyway changing the root type to something an Item fixed the problem for me.