2
votes

I am trying to write a code snippet which would take a QList of QVariants and would populate the list using ListView.

Use cases with types QString, int, bool, double etc. are successful. However, when I am trying to pass char data type as list elements, it is being treated as integer i.e ASCII value is being taken.

Is there any way to make QVariant treat char as char?

Note: I am using Qt5.6.0. I have tried to probe the type by using QVariant::type() expecting it to return QVariant::Char so that I convert it to string and use it. But, QVariant::type() returned QVariant::Int.

int main()
{
    QVariant charVar = 'A';
    qDebug()<< charVar<< "\n";
    return 0;
}

Actual result:

QVariant(int, 65)

Expectation:

QVariant(char, 'A')
1
also, just for completeness sake, the actual type of a char-literal in C is int and not char. In C++ simple char literals like 'a' should be char but multicharacter-literals like 'abcd' are still intPeterT

1 Answers

2
votes

The char type of QVariant is the same as the type of int. If you want to store an actual character, you probably want the type QChar.

Notice that QVariant only has constructors for QChar and int. A C++ char will be cast to int in this case.

To treat your example as a character, you can cast explicitly to QChar

QVariant v1 = QChar('A');
QVariant v2(QVariant::Type::Char);
v2 = 'B';
qDebug() << v1 << v2;
//Output: QVariant(QChar, 'A') QVariant(int, 66)