2013-11-20 34 views
1

我有一個結構,我想要一個類通過一個插槽發射到多個不同的類。但是,並不是所有的班級都應該總是得到的消息。結構中有一個稱爲「ID」的字段,並且基於ID,只有某些對象應該接收結構(與ID匹配的結構)。Qt - 基於信號內容將信號發送到特定對象

目前,我有從QObject派生的發光類和接收類。然後,我將發光類作爲接收類的父類,然後讓父類查看結構ID字段,通過ID查找子元素,然後通過方法將結構發送給它們,即child-> pushData(struct) 。

有沒有更好的方法來做到這一點?我可以根據信號的內容選擇性發送信號嗎?

謝謝你的時間。

回答

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_; 
}; 
+0

您好,感謝您的回覆。所以如果我明白了,你正在委託檢查結構ID到接收類?這不意味着所有的接收器都會得到結構,然後檢查是否應該丟棄它?這不會是無效的,特別是如果結構很大? – trianta2

+0

另外,我看到您在信號/插槽中使用了參考。這安全嗎?到達其他插槽時,發射的參考能否超出範圍? – trianta2

+0

@ trianta2,如果信號使用const引用,它們仍然按值傳遞。因此,這樣做非常安全。 – vahancho