Pregunta

Estoy escribiendo código de prueba que automáticamente iterar a través de todos los Q_PROPERTY de widgets y de algunas propiedades están utilizando tipos que se registran a través de qRegisterMetaType. Si quiero leer / escribir estos en QVariant necesito utilizar QVariant :: UserType al almacenarlos en variante. Hasta aquí todo bien.

Pero cuando quiero prueba de lecturas y escrituras de estas propiedades, lo que necesito saber también su tipo. Para la materia que son tipos qt ya estándar, puedo hacerlo a través de QVariant :: tipo (), pero ya que tengo un montón de usertypes, ¿cómo lograr esto?

A partir de la API de QVariant, manchado este:

bool QVariant::canConvert ( Type t ) const

Pero estoy un poco dudoso que esto dará lugar a tipos incorrectos en el caso de las enumeraciones?

Así que, ¿cuál sería la forma infalible para verificar qué tipo de tipo de usuario se almacena en QVariant?

¿Fue útil?

Solución

Para los tipos definidos por el usuario no es QVariant :: userType () . Funciona como QVariant :: tipo (), pero devuelve la ID del tipo de número entero del tipo definido por el usuario mientras que QVariant :: tipo () siempre volver QVariant :: UserType.

También hay QVariant :: TYPENAME () que devuelve el nombre del tipo como una cadena.

EDIT:

Probablemente depende de cómo haya configurado el QVariant. Directamente a través de QVariant :: QVariant (tipo int, const void * copia) no se recomienda.

decir que tengo tres tipos de esta manera:

class MyFirstType
{ 
    public:
        MyFirstType();
        MyFirstType(const MyFirstType &other);
        ~MyFirstType();

        MyFirstType(const QString &content);

        QString content() const;

    private:
        QString m_content;
};
Q_DECLARE_METATYPE(MyFirstType);

El tercero sin Q_DECLARE_METATYPE

las guardo en QVariant:

 QString content = "Test";

 MyFirstType first(content);

 MySecondType second(content);

 MyThirdType third(content);

 QVariant firstVariant;
 firstVariant.setValue(first);

 QVariant secondVariant = QVariant::fromValue(second);

 int myType = qRegisterMetaType<MyThirdType>("MyThirdType");

 QVariant thirdVariant(myType, &third); // Here the type isn't checked against the data passed

 qDebug() << "typeName for first :" << firstVariant.typeName();
 qDebug() << "UserType :" << firstVariant.userType();
 qDebug() << "Type : " << firstVariant.type();

 [...]

Puedo obtener:

typeName for first : MyFirstType 
UserType : 256 
Type :  QVariant::UserType 

typeName for second : MySecondType 
UserType : 257 
Type :  QVariant::UserType 

typeName for third : MyThirdType 
UserType : 258 
Type :  QVariant::UserType 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top