我有以下代碼,我認為應該在我的 GUI 的 QML 元素中提供一個“后端”C 物件,但似乎失敗了,導致我的 QML 物件的屬性為空。
//Initialize the engine, register the Data_Client object and set the "client" property
QQmlApplicationEngine engine;
QQmlContext *context = engine.rootContext();
const QUrl url(QStringLiteral("qrc:/qml/gui.qml"));
qmlRegisterType<Data_Client>("uri", 1, 0, "Data_Client");
qmlRegisterType<StatusObject>("uri", 1, 0, "StatusObject");
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
Data_Client client();
//Make the Data_Client accessible in the engine root context so its available to all component instances
context->setContextProperty("client", &client);
return app.exec();
在ApplicationWindowgui.qml 檔案的項中,宣告了client屬性,并宣告了以“客戶端”為目標的各種連接:
property Data_Client client
//...
Connections {
target: client
onNew_data:{
//...
}
在Data_ClientC 中,我呼叫emit new_data(QString("test"));但從不觸發 QML 中的處理程式。這以前有效,我認為從根本上來說很簡單,我很高興,所以我還沒有確定我可能破壞了什么。我現在的操作理論是,這不是設定clientrootContext 的屬性,但是我無法在運行時進行檢查,是嗎?我有什么明顯的遺漏嗎?
uj5u.com熱心網友回復:
理論上,可以隨時呼叫 setContextProperty,但當時已經加載的任何 QML 檔案可能不會看到該新屬性。在那之后加載的 QML 檔案將看到它。因此,在呼叫 engine.load() 之前呼叫 setContextProperty 應該可以為您解決問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414851.html
標籤:
