How to access a QAction using the QtTest lib?

蹲街弑〆低调 提交于 2019-12-12 04:22:43

问题


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:

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:


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.



来源:https://stackoverflow.com/questions/40305610/how-to-access-a-qaction-using-the-qttest-lib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!