Qt - 基于信号内容向特定对象发送信号

时间:2013-11-20 17:15:33

标签: qt

我有一个结构,我希望1个类通过一个插槽发送到多个不同的类。但是,并非所有类都应始终获取消息。结构中有一个名为“ID”的字段,根据ID,只有某些对象应该接收结构(与ID匹配的结构)。

目前,我有发射类和接收类派生自QObjects。然后我将emit类作为接收类的父类,然后让父查看结构ID字段,按ID查找子元素,然后通过方法将结构发送给它们,即child-> pushData(struct )。

有更好的方法吗?我可以根据信号的内容有选择地发送信号吗?

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

这是另一种方式:

class ClassReceiving_TypeInQuestion
{
  Q_OBJECT:
  protected:
    explicit ClassReceiving_TypeInQuestion( int idOfType );//....

  public slots:
    void onRxStructSlot( const TypeInQuestion& );

  private:
    //Only called when ID matches....
    virtual void onRxStruct( const TypeInQuestion& ) = 0;
    int idOfType_;    
};

//.cpp
void ClassReceivingStruct::onRxStructSlot( const TypeInQuestion& value )
{
  if( value.id_ == idOfType_ )
  {
    onRxStruct( value );//Could be signal also...
  }
}

任何想要接收信号的类都继承自ClassReceivingStruct,或者:

struct ClassEmitting_TypeInQuestion;

class ClassReceiving_TypeInQuestion
{
  Q_OBJECT:
  public:
    explicit ClassReceiving_TypeInQuestion( 
      ClassEmitting_TypeInQuestion& sender, 
      int idOfType )
    : idOfType
     {
       connect( &sender, SIGNAL(onTxStruct(TypeInQuestion)), 
                this, SLOT(onRxStruct(TypeInQuestion)) ); 
     }
  signals:
    void onTxStruct( const TypeInQuestion& );

  private slots:
    void onRxStruct( const TypeInQuestion& );

  private:
    int idOfType_;    
};

//.cpp
void ClassReceivingStruct::onRxStruct( const TypeInQuestion& value )
{
  if( value.id_ == idOfType_ )
  {
    emit onTxStruct( value );//Could be signal also...
  }
}

class Client
{
  Q_OBJECT

  public:
       enum{ eID = 0 };
      Client( ClassEmitting_TypeInQuestion& sender )
      : receiver_( sender, eID )
      {
         //connect to receiver_....
      }
  private slots:

  private:          
    ClassReceiving_TypeInQuestion receiver_;
};