使用Q_PROPERTY定义从C ++访问QML对象的属性

时间:2011-05-17 15:47:08

标签: qt4 qml qt-quick

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

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

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

谢谢!

解决:

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

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

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

1 个答案:

答案 0 :(得分: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