這是另一種方式:
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_;
};
您好,感謝您的回覆。所以如果我明白了,你正在委託檢查結構ID到接收類?這不意味着所有的接收器都會得到結構,然後檢查是否應該丟棄它?這不會是無效的,特別是如果結構很大? – trianta2
另外,我看到您在信號/插槽中使用了參考。這安全嗎?到達其他插槽時,發射的參考能否超出範圍? – trianta2
@ trianta2,如果信號使用const引用,它們仍然按值傳遞。因此,這樣做非常安全。 – vahancho