簡體   English   中英

在 QML 中獲取 c++ object 並在 javascript 中使用它

[英]Get a c++ object in QML and use it in javascript

I'm making an application in which I'd like to call a function from QML in C++ source, and that c++ function to return me and object which I can use it with the same properties in the javascript part of QML. 我已經建立了聯系和一切。 我嘗試發送 QVariantMap 並嘗試在 javascript 中使用該 object,但我沒有得到該 object 的屬性

有兩種方法可以將基於 QObject 的類型從 C++ 導出到 QML:

  1. 直接從屬性 READer 或 Q_INVOKABLE function 返回獨立的 QObject。 注意,作為屬性返回的 object 擁有 C++ 所有權,Q_INVOKABLE-object 擁有 JS 所有權。 您可以通過http://doc.qt.nokia.com/4.7/qdeclarativeengine.html#setObjectOwnership更改此默認行為。
  2. 返回 QObjects 數組。 在這種情況下,您應該使用 QObjectList、QDeclarativePropertyMap(不是 QVariantMap)或 QAbstractListModel。

您要公開的類必須繼承自 QObject(或 QDeclarativeItem,如果它們是 UI 組件),並且您必須在加載 QML 代碼之前在 main() 或 ZE8801102A40AD89DDCFDCAEBF008D25Z 插件中注冊它們的類型。

看看http://developer.qt.nokia.com/doc/qt-4.7/declarative-tutorials-extending-chapter1-basics.ZFC35FDC70D5FC69D23EZC38

To pass an object from C++ to QML as a function return value, the return value type needs to be QVariant , not QVariantMap , even though that is the type in the C++ code. 所以只需將您的initialize function 簽名更改為

QVariant initialize();

無需更改任何其他內容,然后您就可以訪問屬性。

關於您稍后關於想要調用返回的 object 的方法的評論,這是不可能的; 返回的 object 只是一組名稱-值對。 如果您希望 object 具有id屬性,則需要在返回之前將帶有該鍵的值insert到 C++ 中的QVariantMap中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM