模型-视图服务器
开发一个简单的服务器程序,用于显示和修改在远程对象网络上提供的 QTreeView。
这是与“模型-视图客户端”配套的服务器端应用程序。
QRemoteObjectRegistryHost node(QUrl(QStringLiteral("local:registry")));首先,我们创建一个QRemoteObjectRegistryHost ,其他远程对象将通过它进行连接、注册,并由其进行广播。随后,客户端只需连接到该注册表,即可轻松获取我们创建的模型。
std::unique_ptr<QStandardItemModel> sourceModel = createModel();
QList<int> roles;
roles << Qt::DisplayRole << Qt::BackgroundRole;现在我们需要创建所需的模型。具体的实现细节可在源代码中查看,您可通过点击本页面下方的链接跳转至该源代码。我们还需定义希望向客户端Replica暴露哪些角色。
QRemoteObjectHost node2(QUrl(QStringLiteral("local:replica")), QUrl(QStringLiteral("local:registry")));
node2.enableRemoting(sourceModel.get(), QStringLiteral("RemoteModel"), roles);在此,我们创建QRemoteObjectHost ,使其连接到之前创建的注册表,并向其共享所有远程对象。随后,我们开始将刚刚创建的模型(名称为RemoteModel )进行远程化处理,并在此处传入角色参数。
QTreeView view;
view.setWindowTitle(QStringLiteral("SourceView"));
view.setModel(sourceModel.get());
view.show();接着,我们使用 QTreeView 控件显示该模型。
TimerHandler handler;
handler.model = sourceModel.get();
QTimer::singleShot(5000, &handler, &TimerHandler::changeData);
QTimer::singleShot(10000, &handler, &TimerHandler::insertData);
QTimer::singleShot(11000, &handler, &TimerHandler::changeFlags);
QTimer::singleShot(12000, &handler, &TimerHandler::removeData);
QTimer::singleShot(13000, &handler, &TimerHandler::moveData);为了保持示例的轻量级,该示例会在服务器应用程序启动后不久执行一些自动操作以影响模型。这些更改随后可在服务器端和客户端同时看到。您还可以修改服务器端字段中的文本,并观察客户端的相应更新。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.