How to access a QAction using the QtTest lib?

2019-09-06 18:58发布

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.

1条回答
smile是对你的礼貌
2楼-- · 2019-09-06 19:32

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.

查看更多
登录 后发表回答