C++/QT:"run"一个 QAction

C++/QT: "run" a QAction

本文关键字:run QAction 一个 QT C++      更新时间:2023-10-16

我需要使用 qt,c++,qtest 自动执行 gui 测试(在 eclipse 中(我有一个动态创建的菜单,其中包含动态创建的QActions,我需要从中测试一个"新选项卡"QAction(在菜单内(,这就是他的创建方式:

  m_pNewTabAction = new QAction(QIcon(":/images/add.png"), tr("&New Tab"), this);
  m_pNewTabAction->setShortcut(tr("Ctrl+N"));
  m_pNewTabAction->setStatusTip(tr("Open a new tab"));
  connect(m_pNewTabAction, SIGNAL(triggered()), this, SLOT(NewTab()));

在我的测试类中,我设法使用"findChildren"函数访问私有 QAction 对象 (m_pNewTabAction(,现在我不知道如何"执行"QAction(或者换句话说"添加新选项卡"(我的测试类:

    //Get the actions available for the filemenu
    QList<QAction *> fileactions = filemenu->findChildren<QAction *>();
    //Execute an action??
    fileactions.front()-> //how do I execute my QAction?
我相信

你正在寻找QAction::activate()

void QAction::activate(ActionEvent event)

ActionEventQAction::TriggerQAction::Hover之一。你可能想要QAction::Trigger.

如果菜单项列表是动态填充的,则可能需要对需要使用findChild((或findChildren((查找的任何项调用setObjectName((。添加这个:

m_pNewTabAction->setObjectName("NewTabAction"); 
(

该字符串不需要 tr((,因为它只是内部的。然后在测试中,使用 findChild(( 然后调用 QAction::trigger((:

QVERIFY( filemenu );
QAction* action = filemenu->findChild<QAction*>( "NewTabAction" );
// OR you could look it up from the main window if the names are unique: 
//    QAction* action = mainWindow->findChild<QAction*>( "NewTabAction" );
QVERIFY( action );
action->trigger();

从代码运行 QAction,部分我的代码...

void MainWindow::on_pushButtonExit_clicked()
{        
    quitAction = new QAction(this);
    connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit);
    quitAction->trigger();
}