要实现的功能是QTableview中Item项上右键弹出菜单
这就必然要判断点击右键时鼠标指针是否在QTableView的Item上
若是是QTableWidget能够用itemAt来判断
QTableView经过查看文档 发现有个indexAt函数 返回QModelIndex函数
QModelIndex QTableView::indexAt(const QPoint & pos) const [virtual] Reimplemented from QAbstractItemView::indexAt(). Returns the index position of the model item corresponding to the table item at position pos in contents coordinates.
因而经过以下代码判断鼠标右键单击的时候,鼠标指针是否在item上ui
qDebug()<<ui->tableview->indexAt(ui->tableview->mapFromGlobal(QCursor::pos())).row();
但是发现一些问题:
当鼠标右键点击第一行的上边缘附近 返回0spa
点击第一行中间 返回1 debug
点击最后一行中间就返回 -1指针
也就是说 点击行A的上边缘附近 返回的是A的上一行
只有点击行A的中间返回的才是A行
并非 indexAt函数所描述的那样返回的是当前行
最后发现问题出在:
indexAt函数根据QPoint判断行的时候 是没有把 QTableView的表头去掉的 (HoriziotalHeader和VerticalHeader)
因此 隐藏表头后 就一切正常了
若是不肯意隐藏表头 我是用以下代码 解决的:code
QPoint pt = ui->tableview->mapFromGlobal(QCursor::pos()); int height = ui->tableview->horizontalHeader()->height(); QPoint pt2(0,height); pt+=pt2; qDebug()<<ui->tableview->indexAt(pt).row();
如今debug输出就一切正常了(上面只是针对QtableView上面的horizontal表头不隐藏,若是竖直方向的也没隐藏,那么也要加上其宽度)。blog
以上就是我解决问题的过程。文档