我正在尝试使用 Qt Remote Objects 来创建客户端服务器应用程序。但是遇到了一个问题,说“connectionToSource 为空”。如何设置源连接?
我正在使用 .rep 文件创建服务器。我使用的代码如下:
数据模型
// Rep File (DataModel.rep)
class DataModel {
PROP(double data)
}
服务器代码
// DataBroadcaster class (DataBroadcaster.h)
// DataBroadcaster class inherits DataModelSimpleSource.h (generated from .rep file)
#include "rep_DataModel_Source.h"
class DataBroadcaster : public DataModelSimpleSource
{
Q_OBJECT
public:
DataBroadcaster(QObject *parent = nullptr);
~DataBroadcaster();
void Initialize();
private:
int QScopedPointer<QRemoteObjectHost> remoteHost;
}
// DataBroadcaster.cpp
DataBroadcaster::DataBroadcaster(QObject *parent): DataModelSimpleSource(parent){}
DataBroadcaster::~DataBroadcaster(){}
void DataBroadcaster::Initialize()
{
remoteHost.reset(new QRemoteObjectHost(QUrl(QStringLiteral("local:mydata"))));
remoteHost->enableRemoting(this, "DataModel");
}
// 服务器代码主函数
#include <QCoreApplication>
#include "DataBroadcaster.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
DataBroadcaster server;
server.Initialize();
double count = 0.0;
while(true)
{
server.pushData(count + 0.1);
}
return a.exec();
}
客户代码
// DataModelDataReplica is generated from .rep file used to generate source
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "rep_DataModel_replica.h"
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
// registered as qml type in main
qmlRegisterType<DataModelReplica>("CustomData", 1, 0, "MyData");
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.load(url);
return app.exec();
}
QML 代码
// DisplayPage.qml Added to QML file
import CustomData 1.0
MyData {
id: dataClient
node: Node {
registerUrl: "local:mydata"
}
Button {
id: btn
text: "Server Data"
onClicked: {
// displaying some data from source
btn.text = dataClient.data
}
}
}
执行:
Server code is running
Client code is running but when trying to get data I get following error message in debugger
**"qt.remoteobjects: connectionToSource is null"**
我无法弄清楚我错过了什么。如果有人对如何解决或在哪里寻找有任何想法,请提出建议。