Avoid context menu in empty areas
-
Qt 6.8.0, on my form I have a
QTableView
and aQAction
.
I tried to show the action on the context menu with:ui->table->setContextMenuPolicy(Qt::ActionsContextMenu);
but it shows nothing.
So I ended up to create the menu by myself:QObject::connect(ui->table, &QTableView::customContextMenuRequested, this, [this]() { QMenu *menu = new QMenu; menu->addAction(ui->actionRemove); menu->exec(QCursor::pos()); menu->clear(); });
now it is shown but the problem is it appears also in empty area of the
QTableView
, example:Instead I would like to show it only if the pointer is on a populated area.
That's because it's the way the user can delete a row. I'm aware the row is still selected even in my picture above but it is not user-friendly.Instead, if the menu is shown only when the pointer is on a row it would be more intuitive for the user.
-
Hi,
Check whether there's an item under the cursors and if not, don't show the menu.
-
@SGaist I tried with:
QObject::connect(ui->table, &QTableView::customContextMenuRequested, this, [this]() { qDebug() << ui->table->indexAt(QCursor::pos()); });
in order to understand if there is a valid item but it always returns:
QModelIndex(-1,-1,0x0,QObject(0x0))
even if I click on a cell.
-
QCursor::pos() returns the global position, not the one relative to your widget. QTableView::customContextMenuRequested() gives you a QPoint which you should use: https://doc.qt.io/qt-6/qwidget.html#customContextMenuRequested
-
Use the pos parameter of the signal to get the position of the cursor in the widget's coordinates.
-