QTableWidget - get cell index from cell widget ?

  • Hey

    I have a QLineEdit in my cell that when conencted to return pressed emits self to my function.

    In my function I try doing indexAt(mapToGlobal(mySender->pos())); and then somehow get the index location of where my widget is at. But that does not work... I tried converting from global coordinate to local and even mapTo(xx) but no luck. How can I properly map the coordinate ? Or maybe there is a better way of doing it ?


  • Lifetime Qt Champion

    If you know what cell index is when you call
    setWidget to apply the QLineEdit, you could store it
    in a property
    thelineedit->setProperty("index", xxx)
    and then read it in your function.

  • Except that when I drag drop etc I will lose that data. I have also partly custom drag drop system as well.... So if I could get it from indexAt that would help a lot...

  • Qt Champions 2018

    indexAt() is working correct - when you pass the correct (viewport) coordinates to it...

  • Lifetime Qt Champion

    Did a fast test.
    alt text
    QLineEdits at

        ui->tableWidget->setCellWidget(1, 1, AddEdit());
        ui->tableWidget->setCellWidget(2, 2, AddEdit());
        ui->tableWidget->setCellWidget(3, 4, AddEdit());

    Then in slot

    void MainWindow::OnEnter()
        QLineEdit *line = qobject_cast<QLineEdit *> ( sender() );
        if (!line) return;
        qDebug() << line->pos();
        qDebug() <<  ui->tableWidget->indexAt( line->pos() );

    and output is


    Which seems pretty ok to me ?

  • Hmmmmmmmmm that got me to think a bit more....

    Since my lineEdit was inside a QWidget layouts as child... I tried qDebug() << indexAt(dynamic_cast<QWidget *>(sender->parent())->pos()); and wuaila it worked!

    Hmmmmmm strange that I could not get it directly from QLineEdit but I had to go to top parent widget... ?

    Still works, thanks so much for help!

  • Lifetime Qt Champion

    Just a note
    qobject_cast is preferable to dynamic_cast.

    If the QLineEdit is inside a widget, it means its pos() will be the offset from
    the QWidget (parent) which would be like just a few pixels. ( like 9,9 )
    However, taking Pos() on the parent widget get you the position relative to the TableWidget which is needed for indexAt()


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