2013-11-20 30 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