我想我很简单地解决了这个问题。我创建了一个模板类,它可以将QVariant
包含 a 的 a转换QList<TemplateParameter *>
为QList<QObject *>
.
我还有一个单例,它存储一个QMap<int, Converter *>
,它映射QVariant::userType()
到相应的转换器。
这允许我注册每个类,我想将其存储在属性中,如下所示:
VariantToObjectListConverter::instance()->registerConverter<AnotherQObject>();
然后我可以转换 unknown QVariants
:
QVariant list = object->property("otherObjects");
QList<QObject *> objects = VariantToObjectListConverter::instance()->convert(variant);
这是必要的代码:
class ConverterBase
{
public:
virtual ~ConverterBase() {}
virtual QList<QObject *> convert(const QVariant &variant) const = 0;
};
template<class Object>
class Converter : public ConverterBase
{
public:
QList<QObject *> convert(const QVariant &variant) const
{
QList<Object *> list = variant.value<QList<Object *> >();
QList<QObject *> result;
Q_FOREACH(Object *object, list) result.append(object);
return result;
}
};
class VariantToObjectListConverter
{
public:
Q_GLOBAL_STATIC(VariantToObjectListConverter, instance)
~VariantToObjectListConverter()
{
QHashIterator<int, ConverterBase *> i(m_converters);
while (i.hasNext()) {
i.next();
delete i.value();
}
}
template<class Object>
void registerConverter()
{
QVariant v = QVariant::fromValue<QList<Object *> >(QList<Object *>());
m_converters.insert(v.userType(), new Converter<Object>());
}
QList<QObject *> convert(const QVariant &variant) const
{
ConverterBase *converter = m_converters.value(variant.userType());
if (!converter)
return QList<QObject *>();
return converter->convert(variant);
}
private:
QHash<int, ConverterBase *> m_converters;
VariantToObjectListConverter() {}
};
我现在可以添加一个宏,它调用registerConverter()
,Q_DECLARE_METATYPE
和qRegisterMetaType()
, 这样用户只需调用
REGISTER_TYPE(TypeName)