Exemplo 2: Conexão direta com uma réplica dinâmica

Não há alterações a serem feitas no lado da fonte, pois uma réplica dinâmica afeta apenas a forma como o nó solicitante obtém a réplica. Portanto, utilizamos o código do lado da fonte mostrado no Exemplo 1.

  1. Adicione a geração da réplica ao projeto.

    Como a réplica é obtida dinamicamente, não é necessário um arquivo ` .rep `, ao contrário do Exemplo 1.

  2. Crie o nó remoto e conecte-o ao nó host de origem.

    O código para esta etapa permanece inalterado em relação ao Exemplo 1.

    QRemoteObjectNode repNode; // create remote object node
    repNode.connectToNode(QUrl(QStringLiteral("local:replica"))); // connect with remote host node
  3. Obtenha uma réplica do objeto de origem remoto.

    Em main.cpp, usamos um objeto ` QSharedPointer ` para armazenar uma réplica do objeto remoto e, em seguida, instanciamos um objeto solicitador 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();
    }

A declaração e a definição completas da classe solicitante, ` DynamicClient`, são as seguintes:

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"

// construtor
DynamicClient::DynamicClient(QSharedPointer<QRemoteObjectDynamicReplica> ptr)
    : QObject(nullptr), clientSwitchState(false), reptr(ptr)
{
    //  sinal de conexão para alteração do estado de validade da réplica com inicialização do slot de sinal
    QObject::connect(reptr.data(), &QRemoteObjectDynamicReplica::initialized, this,
                     &DynamicClient::initConnection_slot);
}

// Função para inicializar conexões entre slots e sinais
void DynamicClient::initConnection_slot()
{
    // Conecta o sinal da réplica de origem currStateChanged() ao  slot
    // recSwitchState()  do cliente  para receber o estado atual da fonte:
    QObject::connect(reptr.data(), SIGNAL(currStateChanged(bool)), this,
                     SLOT(recSwitchState_slot(bool)));
   // Conecta o sinal echoSwitchState(..) do cliente ao
    // server_slot(..)  da réplica  para ecoar o estado recebido:
    QObject::connect(this, SIGNAL(echoSwitchState(bool)), reptr.data(), SLOT(server_slot(bool)));
}

void DynamicClient::recSwitchState_slot(bool value)
{
    // Use a propriedade da réplica para obter “currState” da fonte:
    clientSwitchState = reptr->property("currState").toBool();
    qDebug() << "Received source state " << value << clientSwitchState;
   // Emite um sinal para enviar o estado recebido de volta ao servidor:
    Q_EMIT echoSwitchState(clientSwitchState);
}

Quando executado em conjunto com o exemplo do lado do servidor, a saída é idêntica à do Exemplo 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.