I have 3 files (along with CMakeLists.txt
and qrc
):
main.cpp
- CBDialog.qml
- a "base" for my dialog (contains the property definition)BEditorDialog.qml
- a dialog with a label
They contain:
// main.cpp
#include <QApplication>
#include <QQuickView>
#include <QQmlContext>
int main( int argc, char **argv )
{
QApplication app( argc, argv );
QQuickView view;
view.rootContext()->setContextProperty( "myText", "WOW!" ); // expected to work but doesn't
view.setSource( QUrl( "qrc:/BEditorDialog.qml" ) );
view.show();
return app.exec();
}
//BDialog.qml
import QtQuick 2.6
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
Item {
// This property I want to set from C
property string myText
}
// BEditorDialog.qml
import QtQuick 2.6
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
BDialog {
id: root
Label {
id: label
text: root.myText // doesn't work
}
}
If I assign initial value to the myText
property:
property string myText: "MEH!"
this initial value is displayed, but how to assign it from C ? I suspect I should use the setInitialProperties
member function, but I have only Qt 5.12 installed.
Thank you in advance.
CodePudding user response:
You've mixed up context and object. You're setting the property "myText"
on the QQmlContext which is not the root object of your application. To get the root object you can use rootObject() on your QQuickView
and get a QQuickItem
back. On that you can call setProperty().
This works
#include <QApplication>
#include <QQmlContext>
#include <QQuickItem>
#include <QQuickView>
int main(int argc, char **argv)
{
QApplication app(argc, argv);
QQuickView view;
view.setSource(QUrl("qrc:/BEditorDialog.qml"));
// First set the source and then access the rootObject, otherwise it isn't create yet
view.rootObject()->setProperty("myText", "WOW!");
view.show();
return app.exec();
}