[英]How to get a activeFocusItem property in qml from main.cpp?
I'm looking for a way to retrieve qml item properties which are not in type of base types in C++. 我正在寻找一种检索qml项目属性的方法,这些属性不在C ++中的基本类型中。 I've found this:
我发现了这一点:
QWindow *w = (QWindow *)engine.rootObjects().first();
QVariant p = w->property("color");
but the result is a instance of QVariant. 但是结果是QVariant的一个实例。 I want to get properties like
activeFocusItem
. 我想获取诸如
activeFocusItem
属性。
Well, in fact you can get the value of activeFocusItem
if you use the required toT()
function for the QVariant
. 好吧,实际上,如果对
QVariant
使用必需的toT()
函数,则可以获取activeFocusItem
的值。
In you case it should be something like 在你的情况下,它应该像
QQuickWindow *w = (QQuickWindow*) engine.rootObjects().first();
qDebug() << w->activeFocusItem()->property("activeFocus").toBool(); // true obviously
qDebug() << w->activeFocusItem()->property("objectName").toString();
In this code, we're getting the properties activeFocus
and objectName
, but it's just an example. 在这段代码中,我们获得了属性
activeFocus
和objectName
,但这只是一个例子。
Another way, 其他方式,
QQuickWindow *w = (QQuickWindow*) engine.rootObjects().first();
QQuickItem *wi = w->property("activeFocusItem").value<QQuickItem*>();
qDebug() << wi->property("activeFocus").toBool();
qDebug() << wi->property("objectName").toString();
According to the documentation , 根据文档 ,
Because C++ forbids unions from including types that have non-default constructors or destructors, most interesting Qt classes cannot be used in unions.
因为C ++禁止联合包括具有非默认构造函数或析构函数的类型,所以大多数有趣的Qt类不能在联合中使用。 Without QVariant, this would be a problem for QObject::property() and for database work, etc.
如果没有QVariant,这将成为QObject :: property()和数据库工作等问题。
Usually, you interact with C++ using signals. 通常,您使用信号与C ++进行交互。 In that case, when a QML object type is used as a signal parameter, the parameter should use var as the type, and the value should be received in C++ using the
QVariant
type. 在那种情况下,当将QML对象类型用作信号参数时,该参数应使用var作为类型,并且应在C ++中使用
QVariant
类型接收该值。 More info and examples here . 更多信息和示例在这里 。
So QVariant
is necessary and as I stated before the right way of getting QML objects to be used in C++. 因此,
QVariant
是必要的,正如我在获得在C ++中使用QML对象的正确方法之前所述。
I've uploaded a complete example to GitHub. 我已经将完整的示例上传到GitHub。 I hope this may help you.
希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.