2011-05-17 50 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