Add item to ComboBox from C++ at runtime
-
hi, I'm a beginner with qt quick and qml.
I am creating a small application to learn, this application has a comboBox that should be populated at runtime with the list of serial ports found.
I created a class that scans the system and creates the list of serial ports, but how do I change the QML ComboBox at runtime from a C ++ class?someone can help me
-
Expose the list of your serials ports as model in c++ : https://doc.qt.io/qt-5/qtquick-modelviewsdata-cppmodels.html
Then use that model in your QML ComboBox.
-
ok, it works but I wanted to ask in general how to access the objects of the QML UI from the C ++ code.
For example, if I simply wanted to change the text of a Label from C ++, how should I do it? -
There are several ways to achieve this. Read this: https://doc.qt.io/qt-5/qtqml-cppintegration-topic.html
-
This post is deleted!
-
@federico-massimi You don't access QML objects from C++, you access C++ data from QML
-
This post is deleted!
-
@IntruderExcluder
I did exactly as in the link you sent me. But I have a problem, if I do it to set text of a label everything works fine, but if I try to create a
Q_PROPERTY(bool scanStatus READ scanStatus WRITE setScanStatus NOTIFY scanStatusChanged)
to set the state of a checkbox it doesn't work, or rather if I sets the state in the constructor of the Backend class it works, but after that it stops working. It seems that the bind works only in the constructor and not while I use the UI.On the internet I found this solution:
scanControlSwitch.onClicked: { backend.scanStatus = scanControlSwitch.checked; scanControlSwitch.checked = Qt.binding(function () { // restore the binding return backend.scanStatus; } ); }
and it actually works, but it seems very cumbersome.
In other words, to set the status of a UI element I had to create:- a property in the header of the class
- 2 c ++ functions (setter and getter for the property)
- register my backend class in the main.cpp and instantiate it in my qml
- 1 javacritp function to restore that bind after user click
the same thing with QtWidget was done with just one line, possible that there is no simpler way to interact with the UI?
-
Here‘s a pro tip for you 😉
Write your Q_Property Macro
Rightclick it
Select „Generate Missing Q_Properties“
And qt Creator will add all missing functions for you !