2

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')
melpomene
  • 84,125
  • 8
  • 85
  • 148
VivekVar
  • 69
  • 5
  • 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 `int` – PeterT Jun 19 '19 at 09:36

1 Answers1

2

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)
perivesta
  • 3,417
  • 1
  • 10
  • 25
  • Thanks for the quick response dave. I did not look into the constructors of QVariant. This means, the user will have to pass QChar to the list of QVariant in order to work it as char. – VivekVar Jun 19 '19 at 07:37
  • 1
    @VivekVar that depends on your use case I guess. You can also just let the type be `int` and use `toChar()` to convert it back. `QVariant v3 = 'C'; qDebug() << v3.toChar(); //prints 'C'` – perivesta Jun 19 '19 at 07:42