开发者

Retrieve value of QTableWidget cells which are QLineEdit widgets

开发者 https://www.devze.com 2023-02-09 06:40 出处:网络
I create a QLineEdit,set a val开发者_运维知识库idator and put it on the table with this code:

I create a QLineEdit,set a val开发者_运维知识库idator 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...)


When you declare your tmpLineEdit, you should be declaring it as a QLineEdit* instead of a QWidget*. Your loop grabs the widget, casts it to a QLineEdit* and then tries to put it back into a QWidget*. Also, I'd recommend using qobject_cast<QLineEdit*> (or dynamic_cast) so that you can ensure the cast succeeded.

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;
}

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消