我有下面的代码,我认为它应该使一个“后端”C++对象在我的GUI的QML元素中可用,但似乎失败了,从而导致了QML对象的一个属性为null。
//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();在ApplicationWindow文件的gui.qml项中,将声明client属性,并以"client“为目标声明各种连接:
property Data_Client client
//...
Connections {
target: client
onNew_data:{
//...
}在Data_Client C++中,我调用emit new_data(QString("test"));,但从不触发QML中的处理程序。这以前起过作用,而且我认为从根本上来说很简单,所以我还没有确定我可能打破了什么。我现在的操作理论是,这不是设置rootContext的rootContext属性,但是在运行时没有检查,是吗?有什么明显的东西我错过了吗?
发布于 2022-01-17 14:43:06
理论上,可以在任何时候调用setContextProperty,但是在那个时候已经加载的任何QML文件都可能看不到这个新属性。之后加载的QML文件将看到它。因此,在调用setContextProperty ()之前调用engine.load应该可以解决问题。
https://stackoverflow.com/questions/70721888
复制相似问题