How to get the position of QTableWidget when right-clicking?



  • Hello, I have a QTableWidget and want to add context menu to it. I used the following code to locate the row. But during my debugging, the row always gets a value of -1. What's wrong with it?
    Subtype is the name for the QTableWidget

    QModelIndex index = ui->Subtype->indexAt(QCursor::pos());
    int row = index.row();


  • @MasterBlade
    Why do you need row ? to get the item from tableWidget?

    If yes you can do this :

        ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    
        connect(ui->tableWidget, &QTableWidget::customContextMenuRequested, this, [=](QPoint pos) {
            auto item = ui->tableWidget->itemAt(pos);
            if (item) {
                //logic
            } else {
                //logic
            }
        });
    

    Or if you want index you can do this:

    
        ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu);
        connect(ui->tableWidget, &QTableWidget::customContextMenuRequested, this, [=](QPoint pos) {
            auto index = ui->tableWidget->indexAt(pos);
            if (index.isValid()) {
                qDebug() << index.row();
            }
        });
    

Log in to reply
 

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