I have created a toast notification system and when I’m creating a toast object in C++ it creates the object, but gives a ReferenceError because of the “globals” which lives in the root of my main.qml. I was expecting this to work since I’m passing the valid QML engine to the QQmlComponent and that point the QML is up and running and has a proper context.
However, when I’m creating the toast object from QML’s JavaScript, it is created without ReferenceError
Is it an ownership problem? BTW, I’m using Qt5.
ToastNotification.qml:
import QtQuick 2.7
import QtQuick.Controls 2.5
Rectangle {
id: toast
property alias message: text.text
implicitWidth: text.implicitWidth + Math.round(20)
implicitHeight: text.implicitHeight + Math.round(20)
// ReferenceError when ToastNotification.qml is created from C++
color: globals.rsRed
Text {
id: text
anchors.centerIn: parent
text: "I'm a toast notification... yay..."
}
}
This C++ code creates the toast:
QObject* ToastNotificationManager::createToast(const QString& message)
{
QQmlComponent component(mQuickView->engine(), QUrl("qrc:/qml/ToastNotification.qml"), QQmlComponent::PreferSynchronous);
QObject* toast = component.create();
if (toast) {
toast->setProperty("message", message);
// I also set the visual parent of the toast using SetParentItem, but omitted from the example for the sake of simplicity
}
return toast;
}
My main QML code contains something like the followings. The toastButton is there for testing only. It will create the toast object without ReferenceError
Item {
id: toastContainer
QtObject {
id: globals
property color rsRed: "#BE1622"
}
Button {
id: toastButton
text: "Show toast"
onClicked: {
var comp = Qt.createComponent("qrc:/qml/ToastNotification.qml");
var toast = comp.createObject(toastContainer);
console.log(toast);
}
}
}