16,213
社区成员
各位大佬,在开发中,碰到QTableView在空白区域和选中行单击右键时出现的菜单不同,应该怎么实现呢?目前,我通过QTableView派生出一个自定义的TableView,并且设置和创建菜单:
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, &TableView::customContextMenuRequested, this, &TableView::slotCustomContextMenuResponse);
但如上代码实现的菜单,无法区分选中行和空白区域,要怎么才能实现选中行是一个菜单,选空白区域是另一个菜单呢?
[signal] void QWidget::customContextMenuRequested(const QPoint &pos)
This signal is emitted when the widget's contextMenuPolicy is Qt::CustomContextMenu, and the user has requested a context menu on the widget. The position pos is the position of the context menu event that the widget receives. Normally this is in widget coordinates. The exception to this rule is QAbstractScrollArea and its subclasses that map the context menu event to coordinates of the viewport().
See also mapToGlobal(), QMenu, and contextMenuPolicy.
你的signal和slot中的参数QPoint呢?这个就是拿来用的啊。你用QPoint判断
你可以自己重写QTableView的mousePressEvent,如下,只要能区分,剩下你懂得了
void RewriteTable::mousePressEvent(QMouseEvent *event)
{
QModelIndex index = indexAt(event->pos());
if(!index.isValid())
{
//点击了表格的空白区域
}
}