Ejemplo 2: Conexión directa con una réplica dinámica

No hay cambios que hacer en el lado fuente, ya que una Réplica dinámica sólo afecta a cómo el nodo solicitante adquiere la réplica. Por lo tanto, utilizamos el código fuente mostrado en el Ejemplo 1.

  1. Añada la generación de réplicas al proyecto.

    Debido a que la réplica es adquirida dinámicamente, no se requiere un archivo .rep a diferencia del Ejemplo 1.

  2. Cree el nodo remoto y conéctelo al nodo host de origen.

    El código para este paso no cambia respecto al Ejemplo 1.

    QRemoteObjectNode repNode; // create remote object node
    repNode.connectToNode(QUrl(QStringLiteral("local:replica"))); // connect with remote host node
  3. Adquirir una réplica del objeto fuente remoto.

    En main.cpp, utilizamos un QSharedPointer para mantener una réplica del objeto remoto y, a continuación, instanciamos un objeto solicitante de réplica:

    #include <QCoreApplication>
    
    #include "dynamicclient.h"
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        QSharedPointer<QRemoteObjectDynamicReplica> ptr; // shared pointer to hold replica
    
        QRemoteObjectNode repNode;
        repNode.connectToNode(QUrl(QStringLiteral("local:replica")));
    
        ptr.reset(repNode.acquireDynamic("SimpleSwitch")); // acquire replica of source from host node
    
        DynamicClient rswitch(ptr); // create client switch object and pass replica reference to it
    
        return a.exec();
    }

La declaración y definición completa de la clase requestor, DynamicClient, es la siguiente:

dynamicclient.h

#ifndef _DYNAMICCLIENT_H
#define _DYNAMICCLIENT_H

#include <QObject>
#include <QSharedPointer>

#include <QRemoteObjectNode>
#include <qremoteobjectdynamicreplica.h>

class DynamicClient : public QObject
{
    Q_OBJECT
public:
    DynamicClient(QSharedPointer<QRemoteObjectDynamicReplica> ptr);
    ~DynamicClient() override = default;

Q_SIGNALS:
    void echoSwitchState(bool switchState);// this signal is connected with server_slot(..) slot of source object and echoes back switch state received from source

public Q_SLOTS:
    void recSwitchState_slot(bool); // Slot to receive source state
    void initConnection_slot(); // Slot to connect signals/slot on replica initialization

private:
    bool clientSwitchState; // holds received server switch state
    QSharedPointer<QRemoteObjectDynamicReplica> reptr;// holds reference to replica
 };

#endif

dynamicclient.cpp

#include "dynamicclient.h"// constructorDynamicClient::DynamicClient(QSharedPointer<QRemoteObjectDynamicReplica> ptr) : QObject(nullptr), clientSwitchState(false), reptr(ptr) { //señal de conexión para la réplica válida cambiada con la inicialización de la ranura de señales   QObject::connect(reptr.data(), &QRemoteObjectDynamicReplica::initialized, this, &DynamicClient::initConnection_slot); }// Función para inicializar conexiones entre ranuras y señalesvoid DynamicClient::initConnection_slot() { // Conecta la señal de réplica de la fuente currStateChanged() con la  ranura // recSwitchState()  del cliente  para recibir el estado actual de la fuente:    QObject::connect(reptr.data(), SIGNAL(currStateChanged(bool)), this,SLOT(recSwitchState_slot(bool))); //  Conecta la señal echoSwitchState(..) del cliente con // server_slot(..) de  la réplica  para devolver el estado recibido:    QObject::connect(this, SIGNAL(echoSwitchState(bool)), reptr.data(), SLOT(server_slot(bool))); }void DynamicClient::recSwitchState_slot(bool value) { // Utiliza la propiedad de la réplica para obtener "currState" de la fuente:clientSwitchState =  reptr->property("currState").toBool();    qDebug() << "Received source state " << value << clientSwitchState;
    // Q_EMIT echoSwitchState(clientSwitchState); }

Cuando se ejecuta junto con el ejemplo del lado fuente, la salida es idéntica al Ejemplo 1.

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