title: Maintaining signal connections over instance swap Qt5
body: <p>In my <strong>Qt5</strong> program I have an <strong>interface</strong> with some <strong>signals</strong>.</p>
  
  <p>An implementation of this interface is instanciated at start up and the signals are connected to from different parts of the program (many places).</p>
  
  <p>Now I want to <em>delete</em> that instance and <em>create a new instance</em>, possibly from another implementation, and somehow <em>maintain the signal connections</em> so that all the places that receive the signals does not need to care that the implementation changed.</p>
  
  <p>Is there any way to do this elegantly or do I have to change the architecture of program to keep control over all signal connections in one location (a lot of work)?</p>
  
  <p>Example:</p>
  
  <pre><code>//PS: To be regarded as pseudocode at best, as lots of Qt boilerplate
  //    and error handling code has been left out, and lots of bugs are left in :-)
  
  struct MyInterface{
    virtual void doStuff()=0;
   signals:
    void someSignal();
  }
  
  struct MyImpX:public MyInterface{
    void doStuff(){
      qDebug()&lt;&lt;"MyImpX";
      if((random()%100)&lt;5){
        emit someSignal();
      }
    }
  }
  
  struct MyImpY:public MyInterface{
    void doStuff(){
      qDebug()&lt;&lt;"MyImpY";
      if((random()%100)&lt;10){
        emit someSignal();
      }
    }
  }
  
  struct MyWorker{
    QTimer t;
    MyInterface *inst=0;
    MyWorker(MyInterface *inst):
      inst(inst)
    {
      connect(&amp;t,SIGNAL(timeout()),this,SLOT(doStuff()));
      t.start(100);
    }
    void setNewInstance(MyInterface *inst){
      this-&gt;inst=inst;
    }
    void doStuff(){
      if(0!=inst){
        inst-&gt;doStuff();
      }
    }
  }
  
  
  struct MyConsumer{
    public slots:
    void handleIt(){
      qDebug()&lt;&lt;"Handling signal";
    }
  }
  
  
  
  void main(){
   QApplication app;
   MyInterface *inst=new MyImpX();
    MyWorker con(inst);
    MyConsumer i,j,k,l;
    //In this example all the connects are in one place, but
    //in reality they are called from several locations that
    //Are hard to control.
    connect(inst,SIGNAL(someSignal()),&amp;i,SLOT(handleIt()));
    connect(inst,SIGNAL(someSignal()),&amp;j,SLOT(handleIt()));
    connect(inst,SIGNAL(someSignal()),&amp;k,SLOT(handleIt()));
    connect(inst,SIGNAL(someSignal()),&amp;l,SLOT(handleIt()));
    //[ ... At this point some time passes where the signal is working ]
    //Now the instance changes, so the old connections are lost.
    con.setNewInstance(new MyImpY());
    delete inst;
    inst=0;
    //[ ... At this point some time passes where the signal is NOT working ]
   app.exec();
  }
  </code></pre>