Test menu functionality with pytest-qt

test_app.py:15: AttributeError

Issue

I am using pytest-qt to imitate user mouse clicks on a menu that I created in my Qt application. I have read the documentation and stackoverflow, but I am still getting errors when trying to trigger the QAction in my menu.

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None)
    ...
    create_menu_bar()
    ...

    def create_menu_bar(self):
        sheet_one = QtWidgets.QAction("sheet one", self)
        sheet_one.triggered.connect(lambda: self.load_df(sheet_name="sheet one"))
        # more QActions createad

        menu = self.menuBar()
        menu.addAction(sheet_one)
        # drop down list
        sheet_five_menu = menu.addMenu("&sheet five")
        sheet_five_menu.addAction(sheet_five_one)
        sheet_five_menu.addAction(sheet_five_two)
        ...

My current code looks like this:

def test_menu(qtbot):
    window = my_app.MainWindow()
    qtbot.add_widget(window)
    window.show()
    window.findChild(QtWidgets.QAction, 'sheet_one').trigger()

How can I imitate user mouse clicks on my menu using pytest-qt?

The issue is most likely caused by the fact that you are using window.findChild(QtWidgets.QAction, 'sheet_one').trigger() to trigger the QAction. This method searches for a child widget with the specified object name, but in your case, the QAction is not a child widget of the window.

To imitate user mouse clicks on your menu using pytest-qt, you can use the qtbot.mouseClick() method. Here’s an example:

def test_menu(qtbot):
    window = my_app.MainWindow()
    qtbot.add_widget(window)
    window.show()
    
    menu_bar = window.menuBar()
    sheet_one_action = menu_bar.findChild(QtWidgets.QAction, 'sheet_one')
    qtbot.mouseClick(sheet_one_action, QtCore.Qt.LeftButton)

This code retrieves the QAction from the menu bar using findChild(), and then uses mouseClick() to simulate a left mouse click on the QAction.

Make sure to replace 'sheet_one' with the correct object name of your QAction.

This should imitate a user mouse click on your menu using pytest-qt.