QVariant: QVariant in Qt5

Most of the information included were learnt from internet, written down from my memory. If you think I violated your rights, please contact me at Complaint@justin.education, and I’ll deal with it right away.

What is QVariant

The QVariant class acts like a union for the most common Qt data types.

QVariant is a union that contains a bunch of different types, including QString, QSize, QColor… and standard C++ types such as int and float.

Basically, QVariant can be visualized like something shown below:

class  QVariant
    enum Type {
        Bool = QMetaType::Bool,
        Int = QMetaType::Int,
        LongLong = QMetaType::LongLong,
        Double = QMetaType::Double,
        Char = QMetaType::QChar,
        Map = QMetaType::QVariantMap,
    int toInt() const;
    qlonglong toLongLong() const;
    bool toBool() const;
    double toDouble() const;
    float toFloat() const;

Why using QVAriant

  • Standard naming functions may it easier to manage different types

  • Good to use as an argumant of a function.

  • Good to use especially when you trying to save your applications settings in the form

    QMap<QString, QVariant> mySettings;
    • To write the data to file

      QFile file("file.dat");
      QDataStream out(&file);   // we will get the fucking data into the file
      out << map;
    • To read the data from file:

      QFile file("file.dat");
      QDataStream in(&file);    //Note that "in" means app << data;
      in >> map;  

Maybe we gonna include QDataStream in the next RTFM post, it’s often used together with QVariant.

Note that the process of storing Objects is called Serialization, the opposite is called Deserialization.

Besides normal settings, which often presented in forms of QString or Bool, it also support advance data format such as QFont, QRect ,QKeySequence and even QList<>, and the object declared ourselves.

We can also use them in situations like communication between process or in the network, because we can serialize QIODevice, and all of QAbstractSocket, QLocalSocket, QNetworkReply, QProcess are inherited form QIODevice.

How to use QVariant

  • To be continued…