Friday 16 June 2017

TrafficControl: Modifying Existing Station QML Items from C++ (continued)

In the previous blog post, I was able to send a signal from C++ to the QML part of the program. This is necessary to be able to update the QML map when the trains, stations and tracks change.

There are two ways to update the QML parts:
  • Either change the QML object properties directly from C++ (this is generally recommended). However, this approach requires the C++ part to know about the internal structure of the QML part, which will make future updates of QML structure very risky. http://doc.qt.io/qt-5/qtqml-cppintegration-interactqmlfromcpp.html 
  • Use signal-slot to invoke a QML Javascript where the QML object properties are changed. I'll follow this approach for now.
I have a signal/slot relation between C++ and QML part

When the train arrives to the station, tcStation:trainArrival will emit that signal to the QML part:

The slot part in QML will iterate through the QML objects until it finds the corresponding station. 
I followed the example on https://stackoverflow.com/questions/13187439/qml-element-id-access-from-c
When it finds those stations, it will modify them, in this case changing the color to red and the radius to 1000 m.





Now, I need to think through the graphical design of the map elements (tracks, trains and stations), so that they will reflect the relevant information. I'll cover that in future blog posts.

Some notes:
To be able to send data to a QML/JS slot, the parameters must be of the type QVariant (a QVariant acts like a union of the most common Qt data types).

There will be a need for future optimizations in this approach. I may need to save the address/index to the QML items in the C part so that I won't need to iterate through all QML items every time I'm updating any QML item.

I later renamed the slot to qmlStationOccupancySlot

No comments:

Post a Comment