モデルビューサーバー

Remote Objectsネットワーク上で利用可能なQTreeViewを表示し、変更を加えるシンプルなサーバープログラムを開発する。

これは、Model-View Clientに付随するサーバー側のアプリケーションです。

    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 という名前でリモートを開始します。ここでroles引数も渡します。

    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);

この例を軽量に保つために、サーバ・アプリケーションの起動直後にモデルに影響を与えるいくつかの自動アクションを実行します。これらの変更は、サーバ側とクライアント側の両方で見ることができます。サーバ側でフィールドのテキストを変更し、クライアント側でそれが更新されるのを見ることもできます。

プロジェクト例 @ code.qt.io

© 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.