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

QTableWidget contextMenu crashing the application



  • I just created a context menu for my QTableWidget and it is working fine, as long as I request the menu with the mouse on a row.

    If the table is empty or if I put the mouse on a empty space inside the table this will crash my application

    //this is my connect
    connect(ui->table, &QTableWidget::customContextMenuRequested, this, &MainWindow::popupMenuTableShow);
    
    //snnipet of function
    void MainWindow::popupMenuTableShow(const QPoint &pos)
    {
        int i = ui->table->itemAt(pos)->row(); // crashes here
    
    ...
    }
    

    I understand that since I have no row selected the application is expected to crash, but I can't seem to find a solution for this.

    Any help or insight is appreciated.


  • Lifetime Qt Champion

    Hi,

    You don't check the value returned by itemAt which is going to be nullptr if the table is empty.



  • @SGaist Yeah, I went to the documentation and I just solved the problem

    void MainWindow::popupMenuTableShow(const QPoint &pos)
    {
        QTableWidgetItem *item = ui->table->itemAt(pos);
    
        if(item != nullptr)
        {
            int i = item->row();
            ...
        }
    
    ...
    }
    

    Still, thank you.


Log in to reply