QT中删除QtableWidget中的某一行

private:
    QMenu *RightClick;                          //右键点击
    QAction *deleteAction;                      //删除事件(如需要其它事件,可新定义)
    int iDeletcRow;

private slots:
        void RightClickSlot(QPoint pos);               //菜单点击,获取当前位置
        void RightClickDelete(QAction *act);   //得知菜单当前的位置并删除
    QStringList heads;
    heads << QString::fromLocal8Bit("相机号") <tableWidget_list->setColumnCount(heads.size());
    ui->tableWidget_list->setHorizontalHeaderLabels(heads);
    ui->tableWidget_list->setSelectionBehavior ( QAbstractItemView::SelectRows); //设置选择行为,以行为单位
    ui->tableWidget_list->setSelectionMode ( QAbstractItemView::SingleSelection); //设置选择模式,选择单行
    ui->tableWidget_list->horizontalHeader()->setFont(QFont("Times", 12, QFont::Bold));

    ui->tableWidget_list->horizontalHeader()->setStyleSheet("QHeaderView::section{border: 1px solid #6c6c6c;}");

    ui->tableWidget_list->setContextMenuPolicy(Qt::CustomContextMenu);
    RightClick = new QMenu(ui->tableWidget_list);                        //右键点击菜单
    deleteAction = new QAction(QString::fromLocal8Bit("删除"),this);     //删除事件
    RightClick->addAction(deleteAction);                                //将action添加到菜单内

    connect(ui->tableWidget_list,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(RightClickSlot(QPoint)));
    connect(RightClick,SIGNAL(triggered(QAction*)),this,SLOT(RightClickDelete(QAction*)));



void CIClibration::RightClickSlot(QPoint pos)
{
    QModelIndex index = ui->tableWidget_list->indexAt(pos);    //找到tableview当前位置信息
    iDeletcRow = index.row();    //获取到了当前右键所选的行数

    if(index.isValid())        //如果行数有效,则显示菜单
    {
        RightClick->exec(QCursor::pos());
    }
}



void CIClibration::RightClickDelete(QAction *act)
{
    //弹出提示框,看是否删除数据
    QMessageBox message(QMessageBox::NoIcon, QString::fromLocal8Bit("提示"),
                                QString::fromLocal8Bit("是否删除本行数据?"),
    QMessageBox::Yes | QMessageBox::No, NULL);

    //如确认删除
    if(message.exec() == QMessageBox::Yes)
    {
        if(act->text() == QString::fromLocal8Bit("删除"))   //看选中了删除这个菜单
        {
            ui->tableWidget_list->removeRow(iDeletcRow);  //删除掉了表格信息
        }
    }
}

 

得到的效果图如下:

你可能感兴趣的:(c++学习)