首先声明这两个变量
QMenu* m_menu;
QAction *action_setTime;
在要使用的位置中加入
action_setTime = new QAction ( this);
action_setTime->setText(QStringLiteral("Reset last job time"));
m_menu = new QMenu(ui->tableView);
m_menu->addAction(action_setTime);
connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotContextMenu(QPoint)));//添加右键菜单
connect(m_menu,SIGNAL(triggered(QAction*)),this,SLOT(trigerMenu(QAction*)));//响应动作
槽函数 要记得在类里声明槽函数
void XX::slotContextMenu(QPoint pos)
{
QModelIndex index = ui->tableView->indexAt(pos);
if (index.isValid())
{
m_menu->popup(QCursor::pos()); // 菜单出现的位置为当前鼠标的位置
}
}
void XX::trigerMenu(QAction * pos)//响应点击菜单动作
{
action_setTime->setCheckable(true);
action_setTime->setChecked(true);
QModelIndex index = ui->tableView->currentIndex();//获取当前点击位置
int i=index.row();
..... //添加自己的响应的需求
}