Qt SQL: 如何区分double 和int?
Qt SQL: how to differentiate between a double and an int?
我在 Qt 中使用 SQLite 数据库。当用信息填充 QTableWidget 时,我想检查作为 QVariant 收到的值是整数、双精度数还是字符串:
// query something here, put in in var named 'query'
while(query.next()){
// insert new row
for (int i=0; i<columnCount; i++){
if(query.value(i).toInt()!=0){
//add integer table item with special sorting/formatting
}else if(query.value(i).toDouble()!=0){
//add double table item with special sorting/formatting
}else {
//add standard qt table item
}
}
}
问题是当使用 toInt() 时,double 被转换为整数,反之亦然,这就是为什么所有数值都被视为整数或都被视为双精度数的原因,取决于你先测试哪个。
是否可以正确检查数字是双精度数还是整数?
您必须查询 sqlite_master
元数据。
您应该 运行 单独查询字段 type
,条件 name
作为字段名称,tbl_name
作为 table 名称。
请参阅此处了解可用的字段类型:
要测试存储在 QVariant
中的确切类型,您可以使用 type() 函数然后打开它:
switch(query.value(i).type()) {
case QMetaType::Int:
// ....
break;
case QMetaType::Double:
// ...
break;
}
可以找到类型here。
另外,也许@Victor 的回答有它的优点——我不确定 QtSQL 如何处理类型。
我在 Qt 中使用 SQLite 数据库。当用信息填充 QTableWidget 时,我想检查作为 QVariant 收到的值是整数、双精度数还是字符串:
// query something here, put in in var named 'query'
while(query.next()){
// insert new row
for (int i=0; i<columnCount; i++){
if(query.value(i).toInt()!=0){
//add integer table item with special sorting/formatting
}else if(query.value(i).toDouble()!=0){
//add double table item with special sorting/formatting
}else {
//add standard qt table item
}
}
}
问题是当使用 toInt() 时,double 被转换为整数,反之亦然,这就是为什么所有数值都被视为整数或都被视为双精度数的原因,取决于你先测试哪个。
是否可以正确检查数字是双精度数还是整数?
您必须查询 sqlite_master
元数据。
您应该 运行 单独查询字段 type
,条件 name
作为字段名称,tbl_name
作为 table 名称。
请参阅此处了解可用的字段类型:
要测试存储在 QVariant
中的确切类型,您可以使用 type() 函数然后打开它:
switch(query.value(i).type()) {
case QMetaType::Int:
// ....
break;
case QMetaType::Double:
// ...
break;
}
可以找到类型here。
另外,也许@Victor 的回答有它的优点——我不确定 QtSQL 如何处理类型。