我创建了一个 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++ 和所有指针的东西有点生疏……)
最佳答案
当您声明您的 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 是否也属于该类别。
关于c++ - 检索作为 QLineEdit 小部件的 QTableWidget 单元格的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4947300/