Jeff
Jeff

Reputation: 7210

pyQt sub-menu backtrack

I have a menu that has a structure like this:

Elements
    A
    B
    C\
        1\
            a
            b
        2\
            a
            b
    D

where Elements is displayed on the menubar anything with a \ has a sub-menu.

In this example I have two a's. I want to be able to distinguish which a was clicked buy getting a list like this for example ['a', '1', 'C', 'Elements'].

Does Qt have a function where I can look up the top menus, or a way of backtracking?

I don't want to have to write a connection for each QAction in the menu because that would be a lot of extra code and rather redundant I think.

Upvotes: 1

Views: 279

Answers (3)

Jeff
Jeff

Reputation: 7210

I found another way of solving the problem, below, but I'm going with ekhumoro's answer because his was is cleaner I think.

backtrack = [str(event.text())]
previousWidget = event.associatedWidgets()[0]
while previousWidget.__class__.__name__ != 'QMenuBar':
    backtrack.append(str(previousWidget.title()))
    previousWidget = previousWidget.parent()
print backtrack

Upvotes: 0

ekhumoro
ekhumoro

Reputation: 120568

Make use of the QMenu.triggered, QMenuBar.triggered, and QToolBar.actionTriggered signals.

These signals all pass a reference to the action that was triggered, thus avoiding the need to connect each action to an individual slot.

An alternative approach would be to create a subclass of QAction that allows a handler to be passed as an argument to its constructor. All the boiler-plate connection code could then be factored out into the __init__ method. This approach can be more flexible if there are a lot of actions that are re-used in several different menus and toolbars.

Upvotes: 1

Sebastian Negraszus
Sebastian Negraszus

Reputation: 12195

QSignalMapper might be what you are looking for.

Upvotes: 0

Related Questions