Andrey Chernukha
Andrey Chernukha

Reputation: 21808

How to make a context menu disappear without crashing the app?

Please take a look at this picture:

enter image description here

You can see a QTableView with some stupid content and a context menu in the center of it. My issue is if I click the table (no matter which button was pressed) view when that context menu is on (and I expect the context menu to disappear as it happens in Windows program and then appear back in a new place if the right button was pressed) my program immediately crash. I create it like this:

 connect(tableView, SIGNAL(customContextMenuRequested(const QPoint&)),
              this, SLOT(showContextMenu(const QPoint&)));

void MainWindow :: showContextMenu(const QPoint &_point)
{
   QPoint      pos   = tableView->mapToGlobal(_point);
   QModelIndex index = tableView->currentIndex();
   int         row   = index.row();

   QMenu menu;
   menu.addAction("Test 1");
   menu.addAction("Test 2");

   QAction *action =  menu.exec(pos);
   QString text    = action->text();

   if (text == "Test 1")
      qDebug("Test 1");
   else
      if (text == "Test 2")
          qDebug("Test 2");
   else
      qDebug("Vzdroch");
 }

I have no idea why it crashes. There's no such thing as debugger in QtCreator, i.e. it is but installing it is as complicated as launching a rocket to space. What I need is just to handle mouse clicks beyond context menu area as I normally do.

I understand that it might be really difficult for you to find out why it crashes, so I'm gonna ease my question a bit. Is there a way to make that context menu disappear when the mouse goes beyond its area? There's a signal named hovered() in Qt. It is emitted when user mouse is over a widget, so I was searching for a signal, let's call it unhovered(), emitted when user takes mouse off a widget. Unfortunately I failed to find such a signal. Is there a way to let my program know that mouse is off?

Hope I've described my issue fully.

Upvotes: 0

Views: 1412

Answers (1)

Mat
Mat

Reputation: 206679

QMenu::exec returns 0 if no menu item was selected.

You need to check action before you dereference it, otherwise you'll dereference a null pointer which leads to undefined behavior.

QAction *action =  menu.exec(pos);
if (!action) {
  qDebug() << "no menu selected";
} else {
  QString text  = action->text();
  ...
}

Upvotes: 3

Related Questions