简体   繁体   English

为什么 QVariant 将 char 类型视为整数类型?

[英]Why is QVariant treating char type as an integer type?

I am trying to write a code snippet which would take a QList of QVariants and would populate the list using ListView.我正在尝试编写一个代码片段,它将采用 QVariants 的 QList 并使用 ListView 填充列表。

Use cases with types QString, int, bool, double etc. are successful. QString、int、bool、double 等类型的用例是成功的。 However, when I am trying to pass char data type as list elements, it is being treated as integer ie ASCII value is being taken.但是,当我尝试将 char 数据类型作为列表元素传递时,它被视为整数,即正在采用 ASCII 值。

Is there any way to make QVariant treat char as char?有没有办法让 QVariant 将 char 视为 char?

Note: I am using Qt5.6.0.注意:我使用的是 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.我试图通过使用 QVariant::type() 来探测类型,期望它返回 QVariant::Char 以便我将其转换为字符串并使用它。 But, QVariant::type() returned QVariant::Int.但是,QVariant::type() 返回了 QVariant::Int。

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

Actual result:实际结果:

QVariant(int, 65)

Expectation:期待:

QVariant(char, 'A')

The char type of QVariant is the same as the type of int . QVariantchar类型与int的类型相同。 If you want to store an actual character, you probably want the type QChar .如果要存储实际字符,则可能需要QChar类型。

Notice that QVariant only has constructors for QChar and int .请注意, QVariant只有QCharint构造函数。 A C++ char will be cast to int in this case.在这种情况下,C++ char将被强制转换为int

To treat your example as a character, you can cast explicitly to QChar要将您的示例视为字符,您可以显式转换为QChar

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM