检索作为 QLineEdit 小部件的 QTableWidget 单元格的值
我创建一个 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/诺基亚 QT/MoneyTracker-build-simulator/../MoneyTracker/calculator.cpp:11: 错误:无法将“QLineEdit*”转换为 作业中的“QWidget*”
为什么会出现此转换错误?
另一个子问题:将表作为引用传递可以节省内存,对吗?这可能是问题所在吗?我正在为诺基亚智能手机进行开发,我认为按值传递对象是浪费内存...(抱歉,这是一个愚蠢的问题,但我对 C++ 和所有指针的东西有点生疏...)
I create a QLineEdit,set a validator and put it on the table with this code:
ui->moneyTableWidget->setCellWidget(rowsNum, 1, newQLineEdit);
Then I've got another class for manipulating the table's data doing the sum of every value of a column. Here's the code:
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;
}
But the building fails with this error:
/home/testpec/src/nokia
QT/MoneyTracker-build-simulator/../MoneyTracker/calculator.cpp:11:
error: cannot convert ‘QLineEdit*’ to
‘QWidget*’ in assignment
Why this convertion error?
Another subquestion: passing the table as reference saves memory right? Could this be the problem? Im developing for a Nokia smartphone and I think passing the object by value is a waste of memory...(sorry if is a dumb question but I'm a little rusty with C++ and all the pointers stuff...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您声明
tmpLineEdit
时,您应该将其声明为QLineEdit*
而不是QWidget*
。您的循环获取该小部件,将其转换为QLineEdit*
,然后尝试将其放回QWidget*
。另外,我建议使用qobject_cast
(或dynamic_cast
),以便确保转换成功。至于你的第二个问题,通过引用传递可能是一个好主意 - 我知道 Qt 中的一些类(特别是 QImage)使用引用计数和隐式共享,这样你就可以按值传递,而不必担心大副本的影响操作,但我不确定 QTableWidget 是否也属于该类别。
When you declare your
tmpLineEdit
, you should be declaring it as aQLineEdit*
instead of aQWidget*
. Your loop grabs the widget, casts it to aQLineEdit*
and then tries to put it back into aQWidget*
. Also, I'd recommend usingqobject_cast<QLineEdit*>
(ordynamic_cast
) so that you can ensure the cast succeeded.As for your second question, passing by reference is probably a good idea - I know some of the classes in Qt (QImage in particular) use reference counting and implicit sharing so that you can pass around by value without worrying about the implications of large copy operations, but I'm not sure if a QTableWidget is in that category as well.