实现qt中qtableview 已选择行区域右键点击弹出menu

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菜单
发布了17 篇原创文章 · 获赞 22 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/u013255206/article/details/62235052