Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

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

    General and Desktop
    2
    2
    289
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • M
      MasterBlade last edited by

      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();
      
      Taz742 1 Reply Last reply Reply Quote 0
      • Taz742
        Taz742 @MasterBlade last edited by Taz742

        @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();
                }
            });
        

        Do what you want.

        1 Reply Last reply Reply Quote 3
        • First post
          Last post