Qt SQL:如何区分双精度和整型

Qt SQL: how to differentiate between a double and an int?

本文关键字:双精度 整型 何区 SQL Qt      更新时间:2023-10-16

我在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()时,双精度型被强制转换为整数,反之亦然,这就是为什么所有数值都被视为整数或所有双精度型,这取决于您先测试哪个。

是否有可能正确检查该数字是双精度数还是整数?

要测试QVariant中存储的确切类型,您可以使用type()函数,然后打开它:

switch(query.value(i).type()) {
case QMetaType::Int:
    // ....
    break;
case QMetaType::Double:
    // ...
    break;
}

类型可以在这里找到。

也许@Victor的回答也有它的优点——我不确定QtSQL是如何处理类型的

元数据必须查询sqlite_master

您应该为字段type运行一个单独的查询,条件name作为字段名,tbl_name作为表名。

查看这里可用的字段类型:

SQLite常见问题解答