从 C++ 访问 QML 对象的属性没有 Q_PROPERTY 定义

发布于 2024-11-07 23:52:05 字数 681 浏览 4 评论 0原文

我知道,可以定义具有自定义属性的 QObject 并在 QML 环境中公开该对象。但这样,对于每个新属性,我都需要重新编译 C++ 代码。

是否可以进行从 C++/Qt 到 QML 对象的动态绑定? 比如:

//C++ code: 
updateProperty("myQmlObject.any_property", "Hello World");

谢谢!

已解决:

_view->rootContext()->setContextProperty( "cppmessage" , "Hello from C++" );

其中:view是一个QDeclarativeView,并且cppmessage在QML中使用,没有事先声明,例如:“text:cppmessage”

此链接很有用寻找解决方案: http:// xizhizhu.blogspot.com/2010/10/hybrid-application-using-qml-and-qt-c.html

I know, it's possible to define a QObject with custom properties and expose this object in QML environment. But this way, for each new property I'd need to recompile C++ code.

Is it possible, to make a dynamic binding from C++/Qt to QML-objects?
Something like:

//C++ code: 
updateProperty("myQmlObject.any_property", "Hello World");

Thank you!

SOLVED:

_view->rootContext()->setContextProperty( "cppmessage" , "Hello from C++" );

WHERE: view is a QDeclarativeView, and cppmessage is used in QML without prior declaration like: "text: cppmessage"

This link was usefull for finding the solution: http://xizhizhu.blogspot.com/2010/10/hybrid-application-using-qml-and-qt-c.html

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼睛会笑 2024-11-14 23:52:06

是的,这是可以做到的。 链接

// MyItem.qml
import QtQuick 1.0

Item {
    property int someNumber: 100
}

//C++
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, "MyItem.qml");
QObject *object = component.create();

qDebug() << "Property value:" << QDeclarativeProperty::read(object,"someNumber").toInt();
QDeclarativeProperty::write(object, "someNumber", 5000);

qDebug() << "Property value:" << object->property("someNumber").toInt();
object->setProperty("someNumber", 100);

编辑:1
这里列出了 @Valentin 建议的另一种方法
链接

Yes, This can be done. Link

// MyItem.qml
import QtQuick 1.0

Item {
    property int someNumber: 100
}

//C++
QDeclarativeEngine engine;
QDeclarativeComponent component(&engine, "MyItem.qml");
QObject *object = component.create();

qDebug() << "Property value:" << QDeclarativeProperty::read(object,"someNumber").toInt();
QDeclarativeProperty::write(object, "someNumber", 5000);

qDebug() << "Property value:" << object->property("someNumber").toInt();
object->setProperty("someNumber", 100);

Edit:1
Another way to do it , as suggested by @Valentin is listed here
link

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文