Wie QVariant vom Typ QVariant :: Usertype zu überprüfen, ob Art erwartet?

StackOverflow https://stackoverflow.com/questions/3193275

  •  02-10-2019
  •  | 
  •  

Frage

Ich schreibe Code Tests, die automatisch wird Iterierte durch alle Q_PROPERTY die von Widgets und einige Eigenschaften Typen verwenden, die über qRegisterMetaType registriert sind. Wenn ich lesen wollen / schreiben diese in QVariant muss ich QVariant :: Usertype verwenden, wenn sie in Variante speichern. So weit so gut.

Aber wenn ich möchte Test liest und schreibt diese Eigenschaften muß ich auch ihre Art kennen. Für Sachen, die bereits Standard qt-Typen sind, kann ich dies über QVariant :: type (), aber als ich eine Menge usertypes haben, wie würde dies erreicht werden?

Von der api von QVariant, sah ich dies:

bool QVariant::canConvert ( Type t ) const

Aber ich bin ein wenig zweifelhaft, ob dies zu falschen Arten bei Aufzählungen führen wird?

Also, was der sicherste Weg wäre, um zu überprüfen, welche Art von Benutzertyp in QVariant gespeichert?

War es hilfreich?

Lösung

Für benutzerdefinierte Typen gibt es QVariant :: usertype () . Es funktioniert wie QVariant :: type (), aber gibt den Typ id integer des benutzerdefinierten Typs während QVariant :: type () immer wieder zurückkehren QVariant :: Usertype.

Es gibt auch QVariant :: typename () welche Erträge der Name des Typs als String zurück.

EDIT:

Es hängt wahrscheinlich, wie Sie den QVariant gesetzt. Direkt über QVariant :: QVariant (int-Typ, const void * Kopie) abgeraten.

sagen, ich habe drei Arten wie folgt aus:

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

        MyFirstType(const QString &content);

        QString content() const;

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

Die dritte ohne Q_DECLARE_METATYPE

Ich speichere sie in 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();

 [...]

ich:

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 
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top