Qt -- basic class

Posted by Infinitus 8 on Sun, 06 Mar 2022 07:16:41 +0100

Foundation type

Because Qt is a C + + framework, all syntax and data types in C + + are supported in Qt, but Qt also defines some of its own data types (mostly aliases of C + + data types). Let's introduce these basic data types

QT basic data types are defined in #include < qtglobal >

Type namenotesremarks
qint8signed charSigned 8-bit data
qint16signed short16 bit data type
qint32signed short32-bit signed data type
qint64long long int or (__int64)64 bit signed data type, defined as__ int64
qintptrqint32 or qint64The pointer type varies according to the system type. The 32-bit system is qint32 and the 64 bit system is qint64
qlonglonglong long int or (_int64)Defined in Windows as__ int64
qptrdiffqint32 or qint64The 32-bit and 64 bit systems are different according to the type of qint64 system
qrealdouble or floatThe default is double unless the - qreal float option is configured
quint8unsigned charUnsigned 8-bit data type
quint16unsigned shortUnsigned 16 bit data type
quint32unsigned intUnsigned 32-bit data type
quint64Unsigned long int or (unsigned _int64)Unsigned 64 bit data type, defined as unsigned in Windows__ int64
quintptrquint32 or quint64Depending on the system type, the 32-bit system is quint32 and the 64 bit system is quint64
qulonglongUnsigned long int or (unsigned _int64)Defined in Windows as__ int64
ucharunsigned charUnsigned character type
uintunsigned intunsigned int
ulongunsigned longUnsigned long
ushortunsigned shortunsigned short
qsizetypesize_t

Resolution:

q: Qt

int: integer

8: Represents that the integer occupies 8 bits, 8 bits = = 1 byte integer, bits / 8 = = number of bytes, signed 8-bit data: - 128 ~ 127

Different platforms have different rules, which ensure that there must be 32-bit int, 64 bit int in different platforms It is not specified that int must be 4 bytes, but the relationship is specified: short < = int < = long. Int is not necessarily 4 bytes. In order to cross platform, qint8 and qint16 are encapsulated Equal data type

ptr: identifies the position of the array, which can be pointed to by a pointer or subscript

Real: real number 𞓜 decimal, double or float

u: Unsigned

qsizetype: the type of size. The size has no negative number, and the alias is size_t: unsigned long type

Open a separate help documentation program to view assistant QtGlobal

Log output --- log output

For log output in Qt, printf in C and cout in C + + are generally not used. Qt framework provides a class specially used for log output, and the header file name is QDebug

Select compilation Suite (developed with Qt Creator, please select MinGW Minimalist GNU for Windows)

 CMakeLists.txt CMake's engineering files are different from qMake

cmake_minimum_required(VERSION 3.5)

project(untitled LANGUAGES CXX)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

find_package(Qt5Core)

add_executable(untitled
  main.cpp
)
target_link_libraries(untitled Qt5::Core)

 main.cpp 

#Include < qcoreapplication > / / Core QApplication class without ui interface
#include<iostream>
#/ / the header of the log file used to output the < qdebug >
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    //C/C + + output is not recommended, but it can be used
    printf("hello QT\n");
    std::cout<<"hello Qt2"<<std::endl;
    /*Wrong use
    QDebug q;               no matching constructor for initialization of 'QDebug'  No matching constructor              
    q<<"hello debug"<<endl; use of undeclared identifier 'end' */

    //Qt provides a special output method
    qDebug()<<"hello debug";//qDebug() is not a class name
    qWarning()<<"warining";
    qInfo()<<"info";
    qCritical<<""critical;
    qFatal()<<"fatal";      //too few arguments to funtion call,at least argument 'msg' m...  It will directly interrupt the program and cannot output fatal errors in the form of stream
    qDebug()<<"maye"<<"is"<<"good"; //Each output will automatically add a space in the middle and wrap at the end
    return a.exec();
}
/*output*/
hello Qt
hello Qt2
hello debug
warining
info
critical
maye is good

Anonymous function goes to definition: Follow Symbol Under Cursor

Basic classification

  • qDebug: debugging information prompt

  • qInfo: output information

  • qWarning: general warning

  • qCritical: serious error prompt

  • qFatal: fatal error prompt, which will directly interrupt the program

C style output is similar to printf()

qDebug("debug %d %s",50,"hello"); 
qWarning("warning %d",12);
qInfo("info %d",34);
qCritical("critical %d",89);
qFatal("fatal %s","hello");	 //Fatal error will directly interrupt the program -- > program ends abnormally
qDebug()<<"dfs";

/*output*/

debug 50 hello
warning 12
info 34
critical 89
fatal hello                 //It can be output in this way, but when this line of code is executed, the program will be interrupted directly
 Abnormal end of program

C + + style

qDebug()<<"handsome"<<endl;
qInfo()<<"qInfo"<<endl;
qWarning()<<"qWarnning"<<endl;
qCritical()<<"qCritical"<<endl;
#qFatal()<<"qFatal"<<endl; 			// Fatal error cannot be output with < <

String type

C language = > char * (char array is also of char * type) to store strings

C + + = > STD:: String store string

QT = > qbytearray (byte array is regarded as char * of c language, which is just a simple encapsulation of characters without coding), qstring (string in QT with type and coding)

QByteArray

In Qt, QByteArray can be regarded as an upgraded version of char * in C language. When using this type, we can apply for a piece of dynamic memory through the constructor of this class, and open up a memory space for storing the string data we need to process, which can be managed through this class.

Now let's introduce some API functions commonly used in this class. We should form the good habit of actively querying help documents in case of problems

  • Constructor

// Construct an empty object without any data inside
QByteArray::QByteArray();
// Construct the size characters in data to get a byte array object
// If the size==-1 function automatically calculates the string length, the calculation method is: strlen(data)
QByteArray::QByteArray(const char *data, int size = -1);
// Construct a byte array with a length of size bytes and each byte value of ch
QByteArray::QByteArray(int size, char ch);
#include<QByteArray>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    //Parametric structure
    //Byte array: the output is what is put without coding, and the output of one byte is one Chinese three bytes
    QByteArray name("ride the wind and waves");
    //All types of qDebug support output and overload the shift left operator
    qDebug()<<name;

    //Nonparametric structure
    QByteArray str;
    //str<<"hello";   Stream operation is not supported
    //Overloaded assignment operator, can directly assign a string
    str = "hello";    
    qDebug()<<str;
   
    char* str1 = "maye is man";
    QByteArray s(str1);
    qDebug()<<s;
    //The specified length is only 4 characters
    QByteArray s(str1,4);
    qDebug().noquote()<<s; //Output access member without double quotes
    return a.exec();
}
"\xE4\xB9\x98\xE9\xA3\x8E\xE7\xA0\xB4\xE6\xB5\xAA"
"hello"                    //Letters take up only one byte. All English is ascii coded
"maye is man"
maye
  • Data operation -- > add, delete, modify and query

// For other overloaded functions with the same name, please refer to the Qt help document, which is omitted here
QByteArray &QByteArray::append(const QByteArray &ba);       //Append at the end
void QByteArray::push_back(const QByteArray &other);        //For functions like c + +

// For other overloaded functions with the same name, please refer to the Qt help document, which is omitted here
QByteArray &QByteArray::prepend(const QByteArray &ba);      //Add in front
void QByteArray::push_front(const QByteArray &other);

// Insert data and insert ba into the position of the ith byte of the array (starting from 0)
// For other overloaded functions with the same name, please refer to the Qt help document, which is omitted here
QByteArray &QByteArray::insert(int i, const QByteArray &ba);//Insert to specified location

// Delete data
// Delete len characters from the large string and delete them from the pos character. / / from which position do you want to delete them
QByteArray &QByteArray::remove(int pos, int len);
// Deletes n bytes from the end of the character array
void QByteArray::chop(int n);
// Truncate the array from the pos position of the byte array (the front part is left and the rear part is deleted)
void QByteArray::truncate(int pos);
// Empty the data in the object to make it null
void QByteArray::clear();

// String substitution
// Replace the substring before in the byte array with after
// For other overloaded functions with the same name, please refer to the Qt help document, which is omitted here
QByteArray &QByteArray::replace(const QByteArray &before, const QByteArray &after);
#define qout qDebug() / / alias qout
#include<QByteArray>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    char* str1 = "maye is man";
    QByteArray s(str1);
    //Added later
    s.append("ok");
    s.push_back("ok");
    //Add in front
    s.prepend("you");
    s.push_front("1");
    qout<<s;
    s.remove(1,3);       //Delete from the first position and delete 3 characters
    s.chop(4);           //Delete the last 4 characters
    s.truncate(5);       //Start from the fifth position and cut off all the following
    s.clear();           //Empty all
    qout<<s;
    retutn a.exec();
}
/*output*/
"1youmaye is manokok"
"1maye is manokok"
"1maye is man"
"1maye"
""
  • Substring search and judgment

//Both belong to overload, and return true if there is one, and false if there is no one
// Judge whether the byte array contains the substring ba, and return true, otherwise return false
bool QByteArray::contains(const QByteArray &ba) const;
bool QByteArray::contains(const char *ba) const;
// Judge whether the byte array contains the sub character ch, and return true if it contains, otherwise return false
bool QByteArray::contains(char ch) const;

// Judge whether the byte array starts with the string ba and returns true instead of false
bool QByteArray::startsWith(const QByteArray &ba) const;
bool QByteArray::startsWith(const char *ba) const;
// Determine whether the array starts with true and returns with false
bool QByteArray::startsWith(char ch) const;

// Judge whether the byte array ends with the string ba, and return true instead of false
bool QByteArray::endsWith(const QByteArray &ba) const;
bool QByteArray::endsWith(const char *ba) const;
// Judge whether the byte array ends with the character ch, and return true instead of false
bool QByteArray::endsWith(char ch) const;
#include<QByteArray>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QByteArray str("hello welcome learn Qt");
    //Find whether there is Qt substring in the string
    if(str.contains("Qt"))
    {
        qout<<"have Qt";
    }
    else
    {
        qout<<"No, Qt";
    }
    //Whether to start with the specified string
    if(str.startWith("he"))
    {
        qout<<"have he";
    }
    //Whether to end with the specified string
    if(str.endWith("C"))
    {
        qout<<"have C";
    }
    return a.exec();
}

/*output*/
have Qt
 have he
  • Traversal -- > viewing of characters

// Using Iterators 
iterator QByteArray::begin();
iterator QByteArray::end();

// Traversal using arrays
// The value range of i is 0 < = i < size ()
char QByteArray::at(int i) const;
char QByteArray::operator[](int i) const;
//Traversal of characters
//1. Iterator ch: variable str: container
for(auto ch: str)    //The new C++11 standard uses the previous variables to take out the values in the subsequent containers one by one and give them to ch, which can output one by one, and will automatically judge whether it is over or not
{
    qout<<ch;        //The output string only takes' ', and the output character does not take' '
}
for(auto it = str.begin();it!=str.end();it++)
{
    qout<<*it;       //auto == QByteArray::iterator auto type inference
}
//2. You need to know the length of str when using subscript method
for(int i=0;i<str.size();i++)
{
    qout<<str[i];
}
h
e
l
1
o

w
e
l
c
o
m
e

l
e
a
r
n

Q
t
  • View bytes

// Returns the number of characters in a byte array object
int QByteArray::length() const;
int QByteArray::size() const;
int QByteArray::count() const;

// Returns the number of occurrences of a substring ba in a byte array object
int QByteArray::count(const QByteArray &ba) const;
int QByteArray::count(const char *ba) const;
// Returns the number of occurrences of the string ch in the byte array object
int QByteArray::count(char ch) const;
//Get string length
qout<<str.size()<<str.length()<<str.count();    //22 22 22
//View the number of Q occurrences in str
qout<<str.count('Q');                           //1
  • In type conversion c language, integer is formatted as string sprintf()

// Converts a string of type QByteArray to type char *
char *QByteArray::data();
const char *QByteArray::data() const;

// int, short, long, float, double -> QByteArray
// For other overloaded functions with the same name, please refer to the Qt help document, which is omitted here
QByteArray &QByteArray::setNum(int n, int base = 10);   //Which number to convert to QByteArray base: the default is base 10
QByteArray &QByteArray::setNum(short n, int base = 10);
QByteArray &QByteArray::setNum(qlonglong n, int base = 10);
QByteArray &QByteArray::setNum(float n, char f = 'g', int prec = 6);   //Format: 1 Scientific counting method 2 General formal precision: the default is 6 digits after the decimal point
QByteArray &QByteArray::setNum(double n, char f = 'g', int prec = 6);  
[static] QByteArray QByteArray::number(int n, int base = 10);
[static] QByteArray QByteArray::number(qlonglong n, int base = 10);
[static] QByteArray QByteArray::number(double n, char f = 'g', int prec = 6);

// QByteArray -> int, short, long, float, double
int QByteArray::toInt(bool *ok = Q_NULLPTR, int base = 10) const;
short QByteArray::toShort(bool *ok = Q_NULLPTR, int base = 10) const;
long QByteArray::toLong(bool *ok = Q_NULLPTR, int base = 10) const;
float QByteArray::toFloat(bool *ok = Q_NULLPTR) const;
double QByteArray::toDouble(bool *ok = Q_NULLPTR) const;

// std::string -> QByteArray
[static] QByteArray QByteArray::fromStdString(const std::string &str);
// QByteArray -> std::string
std::string QByteArray::toStdString() const;

// Convert all characters to uppercase
QByteArray QByteArray::toUpper() const;
// Convert all characters to lowercase
QByteArray QByteArray::toLower() const;
//Test code
//QByteArray -> char*
QByteArray str("str");
char* pstr = str.data(); //Get char * type

//int... -> QByteArray
str.setNum(520);         //Decimal 520
qout<<str;
str.setNum(520,16);      //Hexadecimal 520 is automatically converted to hexadecimal
qout<<str;

str.setNum(3.1415);
str.setNum(3.1415,'g',2);//The default format is' g ', and the precision is set to 2 [including integer part]
qout<<str;

str.setNum(314.15,'E');
qout<<str;
auto num = QByteArray::number(620); //Returns the object of QByteArray
qout<<num;
/*output*/
"520" --->character string
"208"
"3.1415"
"3.1"
"3.141500E+02"   3.1415*10^2
"620"

 QString

QString is also an encapsulated string, but its internal encoding is utf8. UTF-8 belongs to the Unicode character set. It uses multiple bytes (2 bytes for window and 3 bytes for linux) to represent a character. In this way, it can include the common characters of almost all languages in the world.

Let's introduce some API functions commonly used in this class.

Constructor

// Construct an empty string object
QString();
// Convert char * string to QString type
QString(const char *str);
// Convert QByteArray to QString type
QString(const QByteArray &ba);
// For other overloaded constructors with the same name, please refer to the Qt help document, which is omitted here

Data operation

// Tail append data
QString& append(const QString &str);
QString& append(const char *str);
QString& append(const QByteArray &ba);
void push_back(const QString &other);

// Add data to header
QString& prepend(const QString &str);
QString& prepend(const char *str);
QString& prepend(const QByteArray &ba);
void QString::push_front(const QString &other);

// Insert data, and insert str to the position character of the string (starting from 0)
QString& insert(int position, const QString &str);
QString& insert(int position, const char *str);
QString& insert(int position, const QByteArray &str);

// Delete data
// Delete len characters from the large string, starting from the pos character position
QString& remove(int position, int n);

// Deletes n characters from the end of the string
void  chop(int n);
// Truncate the string from the position position of the byte string (the front part is left and the rear part is deleted)
void  truncate(int position);
// Empty the data in the object to make it null
void  clear();

// String substitution
// Replace the substring before in the byte array with after
// The parameter cs is case sensitive. It is case sensitive by default
QString& replace(const QString &before, const QString &after, Qt::CaseSensitivity cs = Qt::CaseSensitive);

Substring search and judgment

// The parameter cs is case sensitive. It is case sensitive by default
// For other overloaded functions with the same name, please refer to the Qt help document, which is omitted here

// Judge whether the string contains the substring str, and return true; otherwise, return false
bool  contains(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;

// Judge whether the string starts with the string ba and returns true instead of false
bool startsWith(const QString &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;

// Judge whether the string ends with the string ba, and return true instead of false
bool endsWith(const QString &s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;

Traversal

// Using Iterators 
iterator  begin();
iterator  end();

// Traversal using arrays
const QChar  at(int position) const
const QChar  operator[](int position) const;

View bytes

// Returns the number of characters in a byte array object
int  length() const;
int  size() const;
int  count() const;

// Returns the number of occurrences of substring str in a byte string object
// The parameter cs is case sensitive. It is case sensitive by default
int  count(const QStringRef &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;

Type conversion

// int, short, long, float, double -> QString
// For other overloaded functions with the same name, please refer to the Qt help document, which is omitted here
QString& setNum(int n, int base = 10);
QString& setNum(short n, int base = 10);
QString& setNum(long n, int base = 10);
QString& setNum(float n, char format = 'g', int precision = 6);
QString&QString::setNum(double n, char format = 'g', int precision = 6);
[static] QString QString::number(long n, int base = 10);
[static] QString QString::number(int n, int base = 10);
[static] QString QString::number(double n, char format = 'g', int precision = 6);

// QString -> int, short, long, float, double
int QString::toInt(bool *ok = Q_NULLPTR, int base = 10) const;
short QString::toShort(bool *ok = Q_NULLPTR, int base = 10) const;
long QString::toLong(bool *ok = Q_NULLPTR, int base = 10) const
float QString::toFloat(bool *ok = Q_NULLPTR) const;
double QString::toDouble(bool *ok = Q_NULLPTR) const;


// Convert all characters to uppercase
QString QString::toUpper() const;
// Convert all characters to lowercase
QString QString::toLower() const;

String formatting

There is a sprintf() function in C language, and QString also provides an asprintf() function to format strings

 QString res =  QString::asprintf("fileName:%s size:%d","./av.jpg",20);
 qDebug()<<res<<endl;

However, QString also provides another function arg() for formatting string output, which is more convenient

QString arg(const QString &a, int fieldWidth = 0, QChar fillChar = QLatin1Char( ' ' )) const;
QString arg(int a, int fieldWidth = 0, int base = 10, QChar fillChar = QLatin1Char( ' ' )) const;
//Used to fill% 1,% 2... In the string is an integer number in the given format. The first parameter is the number to be filled, the second parameter is the minimum width, the third parameter is base, and the fourth parameter is the character used to fill when the original number length is less than the minimum width

// Sample program
QString str =  QString("%1 %2 %3").arg(1).arg(2);
str = str.arg("hello");
qDebug()<<str<<endl;     //"hello 2 1"

QString text = QString("%1:%2:%3").arg(1,2,10,QChar('0')).arg(35).arg(59);
qDebug()<<text<<endl;    //"01:35:59"

Conversion between different string types

// std::string -> QString
[static] QString QString::fromStdString(const std::string &str);
// QString -> std::string
std::string QString::toStdString() const;

#QString -> QByteArray
// Convert to local code and follow the operating system
QByteArray QString::toLocal8Bit() const;
// The string converted to Latin-1 encoding does not support Chinese
QByteArray QString::toLatin1() const;
// String converted to utf8 encoding format (common)
QByteArray QString::toUtf8() const;

#QByteArray -> QString
//Just use the constructor of QString
#include<QString>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc,argv);
    QString name = Qstring::asprintf("I'm %s,%d years old","maye",18); //Static member functions can be accessed through class names, format strings, and return them to receive with name
    qDebug()<<name;

    //Qt uses placeholders and arg functions
    //Placeholder% 1% 2% 3 indicates its position. It is replaced by arg function: the first will be replaced to the position of% 1 and the second to the position of% 2 
    //The arg function returns a QString, so you can connect it 
    //Note to receive the return value of QString
    auto say1 = Qstring(I'm %1,%2 years old").arg("haha").arc(25);
    auto say2 = Qstring(I'm %2,%1 years old").arg("haha").arc(25);
    qDebug()<<say1;
    qDebug()<<say2;

    QByteArray arr("hello");
    arr = "Hello";        //6 Chinese 3 bytes
    QString str("hello");
    str = "Hello";        //2 the size of this byte is not the number of characters: English letters are one character, and Chinese words are also one character 
    //QString stores Qchar instead of char: a Qchar is two bytes
    QDebug()<<arr.size()<<str.size(); //Same as length() count()
} 

/*output*/

"I'm maye,18 years old"
"I'm haha,25 years old"
"I'm 25,haha years old" //Haha is the first location. Find the location of% 1 in front. Put haha in the location of% 1 to support various types
5 5                     
6 2                     //Byte array output byte number character string output character number

QVariant -- universal type

The class QVariant is magical, or convenient. Many times, several different data types need to be passed. If you use a structure, it is not convenient. The container saves only one data type, and QVariant can handle it all.

The type QVariant acts as the union of the most common data types. QVariant can store many data types of Qt, including QBrush, QColor, QCursor, QDateTime, QFont, QKeySequence, QPalette, QPen, QPixmap, QPoint, QRect, QRegion, QSize and QString, as well as C + + basic types, such as int, float, etc.

Union: assign an int and read a character through char.

Overloaded many types.

Standard type

  • Convert standard type to QVariant type

// This kind of conversion needs to use the constructor of QVariant class. Because there are many, you can consult the Qt help document by yourself. Here are a few simple words
QVariant(int val);
QVariant(bool val);
QVariant(double val);
QVariant(const char *val);
QVariant(const QByteArray &val);
QVariant(const QString &val);
......
    
// Using the set function, you can also set the supported types of data into the QVariant object
// The T type here is the type supported by QVariant
void setValue(const T &value);
// This function behaves exactly like the setValue() function
[static] QVariant fromValue(const T &value);
//Test code
#include<QVariant>
int main(int argc, char *argv[])
{
    QCoreApplication a(argc,argv);
    QVariant var(125);
    QVariant var1("hello");
    var1.setValue(9.62);
    qDebug()<<var<<var1;
    qDebug()<<var.toInt()<<var1.toString();
    qDebug()<<var.Value<int>()<<var1.Value<QString>();//For direct transfer error reporting, you need to explicitly specify the template
    qDebug()<<var.type()<<var.typename();
    return a.exec();
}
/*output*/

String default QString type QVariant(QString,"hello")
QVariant(int,125) QVariant(double,9.62) //Indicate what type it is and what the value is
QVariant::int int                       //Type name type

  Exmple

QVariant v(5);

QVariant v;
v.setValue(5);

QVariant v = QVariant::fromValue(5);

int i = v.toInt();          // i is now 5
QString s = v.toString();   // s is now "5"
  • Judge the actual data type encapsulated in QVariant

Type is an enumeration type

//Get the type and return an enumeration type; Such as QVariant::Int
Type type() const;
//Get type name
const char *typeName() const;
//Get the type name (string) according to the type ID (enumeration)
[static] const char *typeToName(int typeId);
//Get type ID (enumeration) according to type name (string)
[static] Type nameToType(const char *name);
  • Convert the QVariant object to the actual data type

//Before conversion, you can judge whether it can be converted to the corresponding type
bool canConvert(int targetTypeId) const
bool canConvert() const

bool 		toBool() const;
QByteArray 	toByteArray() const;
double 		toDouble(bool *ok = Q_NULLPTR) const;
float 		toFloat(bool *ok = Q_NULLPTR) const;
int 		toInt(bool *ok = Q_NULLPTR) const;
QString 	toString() const;
......

T value() const
//v.value<int>();       

Custom type

In addition to standard types, our customized types can also be encapsulated by QVariant class. The data types stored by QVariant need to have a default constructor and a copy constructor. In order to achieve this function, you must first use Q_DECLARE_METATYPE() macro. This macro is usually placed under the header file where the class declaration is located. The prototype is:

Q_ DECLARE_ Metatype (type) -- > register custom type

The specific steps are as follows:

  • Step 1: define the type and register

//Custom type
class Animal
{
public:
    Animal(){}  //You must have a default constructor
                //The copy constructor must also be available, but if there is no deep or shallow copy, the default one can be used
    Animal(QString name):_name(name){}
    void show()
    {
        qDebug()<<"Animal show name is :"<< _name <<endl;
    }
private:
    QString _name;
};
//Custom type registration
Q_DECLARE_METATYPE(Animal);
  • Step 2: use forvalue() to store objects

int main()
{
    //QVariant vt(Animal("snake")); 	// Custom types cannot be saved through constructors
    QVariant vt;
    //There are two ways to save custom types
    vt = QVariant::fromValue(Animal("dog"));	//①
    vt.setValue(Animal("cat"));					//②
    //If it can be converted to Animal type, it will be converted
    if(vt.canConvert<Animal>())
    {
        Animal animal = vt.value<Animal>();
        animal.show();
    }
	return 0;
}

The API s involved in the operation are as follows:

// If the current QVariant object can be converted to the corresponding template type T, return true; otherwise, return false
bool canConvert() const;
// Converts the current QVariant object to the actual T type
T value() const;
//Test code
class Person
{
public:
    Person()                    //Must have a parameterless constructor
    Person(int age);
    int mage;
};
Person::Person():m_age(0){}
Person::Person(int age):m_age(age){}
Q_DECLARE_METATYPE(Person);     //Custom type, Qt registration
int main(int argc, char *argv[])
{
    QCoreApplication a(argc,argv);
    Person per;
    //A user-defined type cannot be constructed through a constructor. An error is reported: QVariant p(per);
    //Use specific functions
    p.setValue(per);            //Template function void setValue (const T & avalue)
    qDebug()<<p<<p.typename();
    //Get value
    auto pp=p.value<Person>();
    qDebug()<<pp;
    return a.exec();
}
/*output*/
QVariant(Person, ) Person       //No value because there is no overloaded output
0

Topics: C++ Qt