2011-05-17 48 views
3

我知道,可以使用定制属性定义QObject并在QML环境中公开此对象。但这样,对于每个新属性,我都需要重新编译C++代码。从C++ withoun Q_PROPERTY定义访问QML对象的属性

是否有可能从C++/Qt到QML对象进行动态绑定? 类似于:

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

谢谢!

解决:

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

WHERE:视图是QDeclarativeView,和cppmessage在QML使用,无需像现有的声明: “文本:cppmessage”

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

回答

2

是的,这可以做到。 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); 

编辑:1 另一种方式来做到这一点,如@Valentin建议是列在这里 link

+0

谢谢你的答案。悬停我发现,它似乎很安静:setContextProperty。不管怎样,谢谢你! – 2011-05-17 18:01:59

+0

我想这是另一种方式来做到这一点,我会添加到答案。 – Abhijith 2011-05-17 18:18:27