qt - How to re-evaluate c++ function bound to qml property on dependent property change? -
i want bind method of c++ class qml component property , re-evaluate when dependent property changes. next qml component want:
// converter.qml: import qtquick 2.0 qtobject { property double rate: 1 function exchange(amount) { homecoming amount * rate } } if assign result of exchange function property so,
text { text: converter.exchange(100) } the text element automatically update when rate changed. works qml component, not know how c++ class.
i implement functionally equivalent class in c++:
#include <qobject> class convert : public qobject { q_object q_property(double rate read rate write setrate notify ratechanged) public: explicit convert(qobject *parent = 0) : qobject(parent), m_rate(1.0) { } signals: void ratechanged(); public slots: double exchange(double amount) { homecoming m_rate * amount; } double rate() { homecoming m_rate; } void setrate(double r) { m_rate = r; emit ratechanged(); } private: double m_rate; }; the rate property accessible qml, changing not signal qml engine 'exchange' should re-evaluated.
here main.qml:
// main.qml import qtquick 2.1 import qtquick.controls 1.1 import utils 1.0 applicationwindow { width: 300; height: 200 visible: true // converter { id: converter; rate: ratefield.text } cppconverter { id: converter; rate: ratefield.text } column { textfield { id: rateinput; text: '0.41' } textfield { id: amountinput; text: '100.00' } text { id: output; text: converter.exchange(amountfield.text).tofixed(2) } } } if enable cppconverter, output updated when alter amountinput, but not when alter rateinput. if comment-in qml converter element, update works fine.
with qml converter, qml runtime identifies dependency on rate property , re-evaluates exchange function when rate changed. how can indicate qmlengine same in c++ version?
there's no way currently.
i don't think relying on function beingness re-evaluated practice, though. should either explicitly phone call when necessary:
connections { target: converter onratechanged: output.text = converter.exchange(amountfield.text) } or convert exchange() property, , approach declaratively instead of imperatively (code not finish or tested):
class convert : public qobject { // ... q_property(double amount read amount write setamount notify amountchanged) q_property(double exchange read exchange notify exchangechanged) // ... public: double exchange() { homecoming m_rate * m_amount; } private: double m_rate; double m_amount; }; you'd need emit various *changed signals, etc. in appropriate places.
c++ qt binding qml signals-slots
No comments:
Post a Comment