我是 QML 新手,在访问 C++ 对象的 property.property 时遇到问题:
C++、frequency 和 station 都是 Qt 元类型注册对象:
CStation *station = new CStation(...); // QObject
CFrequency *frequency = new CFrequency(..); // QObject
QQmlContext *qmlContext = viewer.rootContext();
qmlContext->setContextProperty("myatcstation", station);
qmlContext->setContextProperty("myfrequency", frequency);
QML:
RowLayout { ....
TextField {
text: myatcstation.toQString(true)
}
}
.... text: myfrequency.toQString(true)
这行得通,但是当我写:text: myatcstation.frequency.toQString(true)
我得到 TypeError: Object [object Object] has no method 'toQString'
frequency
是 CStation
类的属性,设置为 Q_PROPERTY(CFrequency frequency READ getFrequency)
C++ 中的交叉检查工作:
CFrequency test = station->property("frequency").value<CFrequency>();
-- 编辑:弗兰克的回答--
这两个类都是从 QObject
派生的,并且不像教科书那样,因为它们是可复制的。我知道 Identity vs value情况。
频率基本上是一个值对象,但我已将它设为 QObject
基础,因此我可以使用它的属性(参见 Any chance to use non QObject classes with QML )。在示例中,toString
是 Q_INVOKABLE
,非工作情况下的频率返回 QObject
派生的 CFrequency
的拷贝> 对象。
-- 编辑:进一步的发现--
当我更改频率属性以返回 CFrequency*
而不是 CFrequency
时,它也不起作用。当我得到 TypeError: Cannot call method 'toQString' of undefined
时,情况似乎是一样的。 CFrequency
单独工作,但 QML 不理解 myatcstation.frequency
是一个具有 toString
的频率对象。
最佳答案
CFrequency
我假设不是 QObject,否则您不会按值返回它,而是按指针返回。要使 `toQString() 可从 QML 调用,它必须是 Q_INVOKABLE 或槽,这意味着 CFrequency 也必须是 QObject。
如果一个站点只有一个频率,可以考虑将相关信息移动到站点对象中,即将您需要的频率信息作为属性添加到 CStation。
要在频率变化时获取更新,请考虑使用诸如 Q_PROPERTY(QString frequencyAsString READ frequencyAsString NOTIFY frequencyAsStringChanged)
之类的属性,而不是 toQString()
。属性具有通过属性绑定(bind)“内置”的更新机制,但没有好的方法告诉 QML 它应该再次调用 toQString 因为频率发生了变化。
关于c++ - C++对象属性的QML属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19371452/