1

I have a pop-up menu in a QTableWidget (resultTable). In the constructor of my class I set the context menu policy:

resultTable->setContextMenuPolicy(Qt::CustomContextMenu);
connect(resultTable, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(popUpMenuResultTable(QPoint)));

The popUpMenuResultTable function:

void MyClass::popUpMenuResultTable(QPoint pos)
{
    QMenu menu;
    QAction* actionExport = menu.addAction(QIcon(":/new/prefix1/FileIcon.png"), tr("Export"));
    connect(actionExport, SIGNAL(triggered()), this, SLOT(exportResultsTable()));
    menu.popup(pos);
    menu.exec(QCursor::pos());
}

Now, I need to implement a function to test my GUI using the QtTest lib.

How can I produce the same result as a user by right clicking on my resultTable? Basically, I need to get access to the actionExport (QAction) and trigger it.

For example:

enter image description here

I already tried:

QTest::mouseClick(resultTable, Qt::RightButton, Qt::NoModifier, pos, delay);

but it does not show the QMenu.

I'm using Qt 5.3.2.

KelvinS
  • 2,870
  • 8
  • 34
  • 67
  • Have you tried sending a context menu event to the widget? I.e. creating a `QContextMenuEvent` and the sending it with `QCoreApplication::sendEvent()` or `QCoreApplication::postEvent()` – Kevin Krammer Oct 29 '16 at 07:46
  • No, I haven't tried it. Can you provide a brief example of how can I do that? Thanks for the help. – KelvinS Oct 31 '16 at 16:29

1 Answers1

1

Maybe not entirely what you are after but an alternative approach that is easier to test.

Instead of creating the menu manually you register the actions with the widgets and use Qt::ActionContextMenu:

// e.g. in the widget's constructor
resultTable->setContextMenuPolicy(Qt::ActionsContextMenu);

QAction* actionExport = menu.addAction(QIcon(":/new/prefix1/FileIcon.png"), tr("Export"));
connect(actionExport, SIGNAL(triggered()), this, SLOT(exportResultsTable()));
resultTable->addAction(actionExport);

Then you either add an accessor to your widget that returns resultTable->actions() or just make actionExport a member of your class. Once your test code has access to the action it can simply call its trigger trigger() method.

Kevin Krammer
  • 5,159
  • 2
  • 9
  • 22