这是另一种方式:
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