检索QTableWidget单元格中QLineEdit小部件的值

3

我创建了一个QLineEdit,设置了验证器,并使用以下代码将其放在表格中:

ui->moneyTableWidget->setCellWidget(rowsNum, 1, newQLineEdit);

然后,我还有另一个类来操作表格数据,并对列中的每个值进行求和。以下是代码:
int Calculator::calculatePricesSum(QTableWidget &moneyTableWidget){
    double total = 0;
    QWidget *tmpLineEdit;
    QString *tmpString;
    for(int row=0; row<moneyTableWidget.rowCount(); row++){
        tmpLineEdit = (QLineEdit*)moneyTableWidget.cellWidget(row,1);       
        tmpString = tmpLineEdit.text();
        total += tmpString->toDouble();
    }
    return total;
}

但是在构建时出现以下错误:

/home/testpec/src/nokia QT/MoneyTracker-build-simulator/../MoneyTracker/calculator.cpp:11: error: cannot convert ‘QLineEdit*’ to ‘QWidget*’ in assignment

为什么会出现这个转换错误?
另一个子问题:将表作为引用传递可以节省内存,对吗?这可能是问题所在吗?我正在为诺基亚智能手机开发应用程序,我认为通过值传递对象会浪费内存...(如果这是一个愚蠢的问题,那我很抱歉,因为我对C++和所有指针的东西都有点生疏...)
1个回答

11

当你声明tmpLineEdit时,应该将其声明为QLineEdit*而不是QWidget*。你的循环获取了小部件,将其强制转换为QLineEdit*,然后尝试将其放回到QWidget*中。此外,我建议使用qobject_cast<QLineEdit*>(或dynamic_cast)以确保强制转换成功。

int Calculator::calculatePricesSum(QTableWidget &moneyTableWidget){
    double total = 0;
    QLineEdit* tmpLineEdit;
    QString tmpString;
    for(int row=0; row < moneyTableWidget.rowCount(); row++)
    {
        tmpLineEdit = qobject_cast<QLineEdit*>(moneyTableWidget.cellWidget(row,1));
        if(NULL == tmpLineEdit)
        {
            // Do something to indicate failure.
        }
        tmpString = tmpLineEdit->text();
        total += tmpString.toDouble();
    }
    return total;
}

至于你的第二个问题,按引用传递可能是一个好主意 - 我知道Qt中的一些类(特别是QImage)使用引用计数和隐式共享,所以你可以通过值传递而不用担心大量复制操作的影响,但我不确定QTableWidget是否也属于这个类别。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接