Qt - 如何测试 QTableWidget 项的文本是否为整数

Qt - How to test whether the text of QTableWidget item is an integer number or not not?

本文关键字:文本 是否 整数 QTableWidget 何测试 测试 Qt      更新时间:2023-10-16

我正在使用Qt和C++。如果我有QTableWidget,如何测试项目的文本是否为整数?

if(table->item(index, 0)->text().is_integer())
    Qdebug("yes is an integer") ;
else 
    Qdebug("no is not an integer") ;

你这样做就像你做通常的QStringint转换 - QString::toInt ,但你可以忽略返回值。我建议使用这个辅助函数,因为它可以让您了解成功/失败QString::toInt

bool isInt(QString const& str, int base = 10)
{
    bool ok = false;
    str.toInt(&ok, base);
    return ok;
}

用法:

if(isInt(table->item(indice, 0)->text()))
    ...

编辑:我不知道为什么我在这里使用toInt。如果有较大的数字只能用较大的整数数据类型表示(或者您只想处理unsigned数字),请为这些数字创建此函数。

相关文章: