QTableWidget 右键菜单

头文件中:

    QMenu* m_pContextMenu;
    QAction* m_pActionDel;

构造函数中:

ui->tableWidget->setContextMenuPolicy(Qt::CustomContextMenu)
void CreateMenu()
{
    //创建菜单项
    m_pContextMenu = new QMenu(this);
    m_pActionDel = new QAction(this);
    m_pActionDel->setText(QString("删除"));
    m_pContextMenu->addAction(m_pActionDel);

    //菜单项
    connect(m_pContextMenu, SIGNAL(triggered(QAction*)), this, SLOT(SlotMenuClicked(QAction*)));
    bool b = connect(ui->tableWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(tableContexMenuRequested(const QPoint&)));
    int i = 1;

}

槽函数:

void tableContexMenuRequested(const QPoint &pos)
{
    m_pSelectItem = ui->tableWidget->itemAt(pos);
    if(m_pSelectItem != nullptr){
        m_pContextMenu->exec(QCursor::pos());
    }
}

void SlotMenuClicked(QAction *act)
{
    if (act == m_pActionDel)
    {
        int nRow = m_pSelectItem->row();
        QTableWidgetItem* item = ui->tableWidget->item(nRow, 1);
 
        ui->tableWidget->removeRow(nRow);
    }
}

 

posted @ 2022-11-10 10:58  阳光下的小土豆  阅读(2442)  评论(0编辑  收藏  举报