Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Select QTableWidget row when right-clicked



  • I want to know if there is a way to select a QTableWidget row only when you right-click on it that shows a context menu and then deselect it after context menu disappears.
    I want the table to keep the table setSelectionMode to QAbstractItemView::NoSelection and changes it when I customContextMenuRequested and when that is done it goes back to NoSelection mode.


  • Lifetime Qt Champion

    Hi,

    One thing that comes to mind is to interact with the selection model. When you right click, use it directly (not tested though).



  • @SGaist

    I solved the problem by doing this:

    MainWindow::MainWindow(QWidget *parent)
        : QMainWindow(parent)
        , ui(new Ui::MainWindow)
    {
            connect(ui->table, &QTableWidget::customContextMenuRequested, this, &MainWindow::popupMenuTableShow);
    
        ui->table->setSelectionMode(QAbstractItemView::NoSelection);
        ui->table->setFocusPolicy(Qt::NoFocus);
        ui->table->setSelectionBehavior(QTableWidget::SelectRows);
        ui->table->setContextMenuPolicy(Qt::CustomContextMenu);
    
    }
    
    
    //the function
    void MainWindow::popupMenuTableShow(const QPoint &pos)
    {
        QTableWidgetItem *item = ui->table->itemAt(pos);
                              
            if(item != nullptr)
            {    
                int i = item->row();    
        
                ui->table->setSelectionMode(QAbstractItemView::SingleSelection);    
                ui->table->selectRow(i);
            
                QMenu* contextMenu = new QMenu(this);
                contextMenu->deleteLater(); 
        
                connect(contextMenu, &QMenu::aboutToHide, [this]()
                {
                    ui->table->selectionModel()->clear();
        
                    ui->table->setSelectionMode(QAbstractItemView::NoSelection);
                });
    
    //                ...the rest of the function
    
              }
    
    }

Log in to reply