【问题标题】:Qt SQL: how to differentiate between a double and an int?Qt SQL:如何区分 double 和 int?
【发布时间】:2016-01-21 00:35:27
【问题描述】:

我在 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 会被转换为整数,反之亦然,这就是为什么所有数值都被视为整数或都被视为双精度数的原因,这取决于你使用哪一个先测试一下。

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

【问题讨论】:

    标签: c++ qt integer double


    【解决方案1】:

    您必须向sqlite_master 查询元数据。

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

    查看此处了解可用的字段类型:

    SQLite Frequently Asked Questions

    【讨论】:

    • 我选择了@Rostislav 的回答,这似乎解决了问题。无论如何感谢您的帮助,您提供的链接仍然很有帮助。
    【解决方案2】:

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

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

    类型可以在here找到。

    另外,也许@Victor 的回答有其优点 - 我不确定 QtSQL 如何处理这些类型。

    【讨论】:

      猜你喜欢
      • 2015-06-08
      • 2014-06-26
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多