[SOLVED] Access a cellwidget of a tablewidget..



  • So lets say we have a tablewidget and we have added a qtimeedit to a cellwidget of the tablewidget via

    @QTimeEdit *end_time=new QTimeEdit(this);
    end_time->setTime(QTime(12,04));
    ui->tableWidget->setCellWidget(0, 3, end_time);@

    How can i access it later to see the current qtime?



  • First option is to keep track of the widgets yourself, of course. But you can also access them using something like:
    @
    QModelIndex index = tableWidget->model()->index(row, column);
    QWidget* theCellWidget = tableWidget->indexWidget(index);
    @



  • [quote author="Andre" date="1380538325"]First option is to keep track of the widgets yourself, of course. But you can also access them using something like:
    @
    QModelIndex index = tableWidget->model()->index(row, column);
    QWidget* theCellWidget = tableWidget->indexWidget(index);
    @
    [/quote]

    Yes but u can't use thecellwidget->time() because we didn't declared that the cellwidget it a qtimeedit..

    I tried someting like
    @QModelIndex index = ui->tableWidget->model()->index(i, 2);
    QTimeEdit* theCellWidget = ui->tableWidget->indexWidget(index);@

    but gives an error of
    @C2440: 'initializing' : cannot convert from 'QWidget *' to 'QTimeEdit *'
    Cast from base to derived requires dynamic_cast or static_cast@



  • Well, the error is quite clear, I'd say. It even proposes a solution... Note that you won't have this problem if you keep track of the widgets yourself.


  • Lifetime Qt Champion

    Hi,

    You need to use qobject_cast, (since you are using QObject derived classes) you can't just assign a pointer from one type to another like that



  • Yep this worked

    @QModelIndex index = ui->tableWidget->model()->index(i, 2);
    QTimeEdit* theCellWidget = qobject_cast<QTimeEdit *>(ui->tableWidget->indexWidget(index));
    qDebug () << theCellWidget->time().toString();@

    ;)



  • Line 3 will cause a crash if line 2 failed. Always check the result of a dynamic cast (and qobject_cast is a dynamic cast)!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.