【发布时间】:2013-10-15 00:30:28
【问题描述】:
我是 QML 新手,在访问 C++ 对象的 property.property 时遇到问题:
C++、频率和电台都是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 的频率对象。
【问题讨论】: