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 ?

    Regards
    Dariusz


  • Lifetime Qt Champion

    Hi
    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

    Hi
    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

    QPoint(100,30)
    QModelIndex(1,1,0x0,QTableModel(0x1f1d13ea7d0))
    QPoint(200,60)
    QModelIndex(2,2,0x0,QTableModel(0x1f1d13ea7d0))
    QPoint(400,90)
    QModelIndex(3,4,0x0,QTableModel(0x1f1d13ea7d0))
    

    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

    @Dariusz
    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()


Log in to reply