我正在開發一個 QtQuick 2 應用程式(Qt 版本 6.2.3)。我創建了一個 C 類(我們稱這個類為“示例”),其中包含我的應用程式應該處理的資料。這個類可以被實體化多次,代表要顯示的不同資料集。
class ExampleObject : public QObject {
Q_OBJECT
Q_PROPERTY(QString property1 MEMBER property1 CONSTANT)
...
public:
QString property1;
};
Q_DECLARE_METATYPE(ExampleObject*)
我希望能夠通過 QML 顯示此類的實體,因此我創建了一個“示例”自定義組件,其屬性指向包含我要顯示的資料的示例 C 物件。
ExampleComponent {
property var exampleCppObject // exampleCppObject is a pointer to an instance of ExampleObject
Label {
text: exampleCppObject.property1
}
}
為了能夠更改 QML 組件使用的 Example 實體,我創建了函式來“重新初始化”和“更新”組件:
ExampleComponent {
property var exampleCppObject // exampleCppObject is a pointer to an instance of ExampleObject
property string textToDisplay
function update() {
textToDisplay=Qt.binding(() => exampleCppObject.property1);
}
function reinitialize() {
textToDisplay=""
}
Label {
text: textToDisplay
}
}
I call these functions after changing or deleting the Example object pointed by ExampleCppObject, and this works quite fine. But I feel like this isn't best practice, and it seems to me that I am doing things wrong.
What are better ways of connecting C to QML, in the situation I described?
Edit: my main.cpp essentially consists in:
MainModel mainModel;
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("mainModel", &mainModel);
engine.load(QStringLiteral("qrc:/main.qml"));
Where mainModel is an object which can create different instances of ExampleObject while the application is running.
uj5u.com熱心網友回復:
您可以優化系結textToDisplay,這樣您就不必呼叫upateandreinitialize函式,這似乎是您所追求的問題:
property var exampleCppObject
property string textToDisplay : exampleCppObject ? exampleCppObject.property1 : ""
如果以后需要更復雜的邏輯,也可以使用大括號:
property string textToDisplay: {
console.log("log me everytime the binding is reevalutated")
if(condition1)
return "invalid"
else if(condition2)
return exampleCppObject.property2
else
return exampleCppObject.property1
}
最好的部分是 QQmlEngine 實際上會重新評估此系結中使用的每個屬性的系結(具有通知信號),因此如果設計正確,您可以在很大程度上不理會系結(這意味著您不需要update和reinitialize功能)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/448146.html
