QTableView在空白区域和选中行单击右键时出现的菜单不同,应该怎么实现呢?

lwei2 2021-09-13 10:41:15

各位大佬,在开发中,碰到QTableView在空白区域和选中行单击右键时出现的菜单不同,应该怎么实现呢?目前,我通过QTableView派生出一个自定义的TableView,并且设置和创建菜单:

setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, &TableView::customContextMenuRequested, this, &TableView::slotCustomContextMenuResponse);

但如上代码实现的菜单,无法区分选中行和空白区域,要怎么才能实现选中行是一个菜单,选空白区域是另一个菜单呢?

...全文
304 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
donwmufromdying 2021-09-14
  • 打赏
  • 举报
回复 1

[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())
    {
        //点击了表格的空白区域
    }
}
lwei2 2021-09-14
  • 举报
回复
@溪渣渣_梁世华 现在区分是能区分了,但是要怎么实现在选中行时单击右键弹出的菜单和选中空白时单击右键弹出的菜单,还是不太明白怎么做到两个菜单不同?
  • 举报
回复 1
@lwei2 抱歉,最近顾着中秋去浪没注意看社区了,你要知道一件事情,QT,无论什么,都能够自己重写,你自己重写菜单就行QMenu这个类,区分了,只要他在那个区域右键,就弹出相对应的菜单就行。细节网上有

16,213

社区成员

发帖
与我相关
我的任务
社区描述
Qt 是一个跨平台应用程序框架。通过使用 Qt,您可以一次性开发应用程序和用户界面,然后将其部署到多个桌面和嵌入式操作系统,而无需重复编写源代码。
社区管理员
  • Qt
  • 亭台六七座
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧