1.先设置tableview 样式(ui.tv_searchList 为tableview控件)
//比较重要 只有这样设置 才能使用信号SIGNAL(customContextMenuRequested(QPoint))
ui.tv_searchList->setContextMenuPolicy(Qt::CustomContextMenu);
//设置tableview一次只能可选一行
ui.tv_searchList>setSelectionBehavior(QAbstractItemView::SelectRows);
ui.tv_searchList>setSelectionMode(QAbstractItemView::SingleSelection);
2.实例menu (注意menu设为tableview的子控件)
action_fillUserInfo = new QAction ( this);
action_fillUserInfo ->setText ( QStringLiteral( "设置密码" ));
popMenu = new QMenu(ui.tv_searchList);
popMenu->addAction(action_fillUserInfo);
3.信号槽编写
新建信号连接
connect(ui.tv_searchList, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(slotContextMenu(QPoint))); //添加右键菜单
信号直接用
曹函数需要自己实现
void DeviceImportDialog::slotContextMenu(QPoint pos){
QModelIndex index = ui.tv_searchList->indexAt(pos);
if (index.isValid())
{
popMenu->exec(QCursor::pos()); // 菜单出现的位置为当前鼠标的位置
}
}
附:
action_fillUserInfo 为QAction
popMenu 为QMenu
效果:
能在tableview有可选择行的情况下弹出menu菜单