Question about accessing QML Objects from C++
-
Hi, I started writing my first QT application and have a question about accessing QML objects.
In the Interacting with QML Objects from C++
documentation, it states in red:
"Warning: Although it is possible to access QML objects from C++ and manipulate them, it is not the recommended approach, except for testing and prototyping purposes. "My goal is to launch a window if the program detects a certain file in a directory. Otherwise, it will load the main.qml file. I wanted to manipulate some text and visibility of some objects if the application detects this file. If it is against best practice to access QML objects from C++, what is the alternative? I have a massive WinForms background and everything is updated through C#.
Thank you for your time and help.
-
Hi,
Is this detection done at the application startup ?
As you wrote, you want to show a Window or load a QML file. Can you give more precisions about that ?
-
The alternative is to just expose that information to the QML through the C++ code.
Define a
Q_PROPERTY(bool certainFileIsInDirectory ...)
and conditionnally show your window and modify your text in QML depending on that property.Your C++ shouldn't be aware of your QML layer to minimize the coupling. Expose your data in C++, display it and interact with it in QML.
A video explaining it : https://youtu.be/vzs5VPTf4QQ?t=23m20s
-
Edit: OK I think I found it by looking through examples (should of done this from the start). I have to update the UI through states.
@SGaist Yes I want the detection to be done at startup. I want to replace the main.qml file with another qml file at startup. I want it all to be in one window because I do not want my app to create separate windows because it is going onto an embedded board. From what I understand, I think you need to create a view and replace the main.qml? Can you confirm this? Or should I have a bunch of rectangles in the main.qml file and change visibility of them? Sorry if you don't understand because I also do not understand QT at all.
-
I was merely ensuring that I understood your intentions correctly. As @GrecKo wrote, and I would have given the same advice, your detection code should be independent of your UI. Mixing the information you gather with states rather than creating different QML files looks to be a good way to get your application working the way you want.