模型-视图服务器
开发一个简单的服务器程序,用于显示和更改远程对象网络上的 QTreeView。
这就是与Model-View 客户端配套的服务器端应用程序。
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 widget 显示模型。
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);
为了使示例保持轻量级,它会在服务器应用程序启动后不久执行一些自动操作来影响模型。服务器和客户端都能看到这些变化。您还可以在服务器端更改字段中的文本,并在客户端看到更新。
© 2025 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.