我需要从SomeClass :: fireSignal成员函数触发不同的信号,具体取决于它的参数类型。我看到的解决方案是使用Qt元系统。这样的任务有更正确的解决方案吗?请帮忙。提前谢谢。
class SomeClass : public QObject
{
Q_OBJECT
public:
void fireSignal(BaseClass *param) {
if(param->metaObject->className() == "DerivedClass1") {
emit derivedClass1Signal(param)
}
if(param->metaObject->className() == "SecondDerivedClass") {
emit secondDerivedClassSignal(param)
}
if(param->metaObject->className() == "OtherDerivedClass") {
emit otherDerivedClassSignal(param)
}
}
signals:
void derivedClass1Signal(DerivedClass1 *param);
void secondDerivedClassSignal(SecondDerivedClass *param);
void otherDerivedClassSignal(OtherDerivedClass *param)
};
答案 0 :(得分:1)
也许试试:
class SomeClass : public QObject
{
Q_OBJECT
public:
void fireSignal(BaseClass *param) {
if(param->metaObject->className() == DerivedCass::staticMetaObject.className()) {
emit sig(qobject_cast<DerivedClass*>(param);
}
if(param->metaObject->className() == SecondDerivedClass::staticMetaObject.className()) {
emit sig(qobject_cast<SecondDerivedClass*>(param);
}
if(param->metaObject->className() == OtherDerivedClass::staticMetaObject.className()) {
emit sig(qobject_cast<OtherDerivedClass*>(param);
}
}
signals:
void sig(DerivedClass1 *param);
void sig(SecondDerivedClass *param);
void sig(OtherDerivedClass *param)
};
答案 1 :(得分:0)
一般来说,这是好的。您可以进行一些改进,但这将取决于您如何使用这些信号。例如,如果所有三个都连接到相同的插槽,则可以在此处减少代码,留下一个具有一个参数的信号,该参数是基类的指针:
class SomeClass : public QObject
{
Q_OBJECT
public:
void fireSignal(BaseClass *param) {
emit derivedClassSignal(param);
}
signals:
void derivedClassSignal(DerivedClass1 *param);
};
但是,从发件人的代码中删除支票将强制您将其包含在接收者的代码中(即检查传递了哪种确切的派生类型)。但是,如果每个信号都连接到不同的插槽,并且这些插槽只需要特定类型的参数,那么这将不起作用,并且您的方法会更好。