How to get the name of a QMenu Item when clicked?

artomason

I have a few actions in a QMenu that I'm trying to connect to a single method; there are additional actions that are unrelated.

import sys
from PyQt5.QtWidgets import *


class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()

        layout = QGridLayout(self)
        self.menu_bar = QMenuBar()
        self.menu = QMenu('MENU', self)

        self.menu_action = QAction('Option #1', self)
        self.menu_action.setData('option1')
        self.menu_action.triggered.connect(self.actionClicked)

        self.menu.addAction(self.menu_action)
        self.menu_bar.addMenu(self.menu)
        layout.addWidget(self.menu_bar)

    def actionClicked(self, action):
        print(action)

        try:
            print(action.text())
        except AttributeError as e:
            print(e)

        try:
            print(action.data())
        except AttributeError as e:
            print(e)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 300, 100)
    window.show()
    sys.exit(app.exec_())

I was wondering how I can tell which of the actions was clicked when the method is called. Currently I'm trying to use self.menu_action.setData() to give the action a cleaner name for the receiving method, but that does not seem to be working properly.

eyllanesc

A possible solution is to use the sender() method that returns the QObject that emits the signal, in this case the QAction:

import sys
from PyQt5 import QtCore, QtWidgets


class Window(QtWidgets.QWidget):
    def __init__(self):
        super(Window, self).__init__()

        layout = QtWidgets.QGridLayout(self)
        menubar = QtWidgets.QMenuBar()
        filemenu = menubar.addMenu('MENU')

        filemenu.addAction('Option #1', self.actionClicked)
        filemenu.addAction('Option #2', self.actionClicked)
        layout.addWidget(menubar)

    @QtCore.pyqtSlot()
    def actionClicked(self):
        action = self.sender()
        print('Action: ', action.text())


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 300, 100)
    window.show()
    sys.exit(app.exec_())

If you are going to connect all the QActions of the QMenu then you can use the triggered signal of the QMenu, this sends the QAction that was pressed.

import sys
from PyQt5 import QtCore, QtWidgets


class Window(QtWidgets.QWidget):
    def __init__(self):
        super(Window, self).__init__()

        layout = QtWidgets.QGridLayout(self)
        menubar = QtWidgets.QMenuBar()
        filemenu = menubar.addMenu('MENU')
        filemenu.triggered.connect(self.actionClicked)
        filemenu.addAction('Option #1')
        filemenu.addAction('Option #2')
        layout.addWidget(menubar)

    @QtCore.pyqtSlot(QtWidgets.QAction)
    def actionClicked(self, action):
        print('Action: ', action.text())


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 300, 100)
    window.show()
    sys.exit(app.exec_())

Update:

The QAction triggered signal is different from the QMenu triggered signal, in the case of the first one it sends a Boolean value that indicates if the QAction is checked (by default a QAction is not checkable, if you want to activate it you must use setCheckable(True)) and in the second case it sends the QAction that was pressed that belongs to the QMenu. That's why you always get False, if you do not want to have that problem you have to use my first method using sender(). On the other hand in Qt very rarely you will have to use try-except, in reality you should never use it in the world of Qt since that has an additional cost that Qt does not want, and on the other hand it hides the cause of the errors , as a recommendation use try-except when there is no other solution, and in the case of Qt there will almost always be another option.

import sys
from PyQt5.QtWidgets import *


class Window(QWidget):
    def __init__(self):
        super(Window, self).__init__()
        layout = QGridLayout(self)
        self.menu_bar = QMenuBar()
        self.menu = QMenu('MENU', self)

        self.menu_action = QAction('Option #1', self)
        self.menu_action.setData('option1')
        self.menu_action.triggered.connect(self.actionClicked)

        self.menu.addAction(self.menu_action)
        self.menu_bar.addMenu(self.menu)
        layout.addWidget(self.menu_bar)

    def actionClicked(self, checked):
        action = self.sender()
        print(action.text())
        print(action.data())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.setGeometry(600, 100, 300, 100)
    window.show()
    sys.exit(app.exec_())

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to get data of hashmap of custom gridview adapter when clicked on gridview item?

分類Dev

Android how to change bottom navigation item color when button is clicked

分類Dev

UWP Get Clicked Item in DataTemplate

分類Dev

print currently selected item when item clicked

分類Dev

Getorgchart - Get name of clicked Node

分類Dev

How to get a specific data value in a data table when clicked - VueJS?

分類Dev

how to get tab to stick open in html when clicked on

分類Dev

Running script with parameter when item is clicked

分類Dev

Opening a new fragment when a ListView item is clicked

分類Dev

incrementing position when clicked an item in jquery

分類Dev

Get a reference to clicked item with MaterialUI and React

分類Dev

Get current clicked item values in jquery

分類Dev

How do I switch from one fragment to another when a list item is clicked?

分類Dev

Call function to remove an item when link is clicked for each item in list

分類Dev

ROBLOX Get name of a player that clicked a brick

分類Dev

How to select (this) image when clicked?

分類Dev

How to get which element was clicked?

分類Dev

How to Change the IconSize for Actions in QMenu?

分類Dev

Get selected title when image is clicked in dropdown

分類Dev

Selecting respective item in drop down list when edit button is clicked

分類Dev

Make menu go away when an item is clicked on mobile/tablet

分類Dev

Filtering Listview not showing correct result when listview item is clicked on Android

分類Dev

How to get id of pause button along with play button id when play button is clicked?

分類Dev

How to get VBA to run through the click of a link or once clicked in Outlook email when someone else recieves the email?

分類Dev

How to get name when roll number is given in pandas

分類Dev

JavaFX how to clear TextField when mouse is clicked on it

分類Dev

How to hide navbar when clicked ouside of it

分類Dev

How keep tooltip when is clicked on EditorFor?

分類Dev

how to open particular fragment when notification is clicked

Related 関連記事

  1. 1

    How to get data of hashmap of custom gridview adapter when clicked on gridview item?

  2. 2

    Android how to change bottom navigation item color when button is clicked

  3. 3

    UWP Get Clicked Item in DataTemplate

  4. 4

    print currently selected item when item clicked

  5. 5

    Getorgchart - Get name of clicked Node

  6. 6

    How to get a specific data value in a data table when clicked - VueJS?

  7. 7

    how to get tab to stick open in html when clicked on

  8. 8

    Running script with parameter when item is clicked

  9. 9

    Opening a new fragment when a ListView item is clicked

  10. 10

    incrementing position when clicked an item in jquery

  11. 11

    Get a reference to clicked item with MaterialUI and React

  12. 12

    Get current clicked item values in jquery

  13. 13

    How do I switch from one fragment to another when a list item is clicked?

  14. 14

    Call function to remove an item when link is clicked for each item in list

  15. 15

    ROBLOX Get name of a player that clicked a brick

  16. 16

    How to select (this) image when clicked?

  17. 17

    How to get which element was clicked?

  18. 18

    How to Change the IconSize for Actions in QMenu?

  19. 19

    Get selected title when image is clicked in dropdown

  20. 20

    Selecting respective item in drop down list when edit button is clicked

  21. 21

    Make menu go away when an item is clicked on mobile/tablet

  22. 22

    Filtering Listview not showing correct result when listview item is clicked on Android

  23. 23

    How to get id of pause button along with play button id when play button is clicked?

  24. 24

    How to get VBA to run through the click of a link or once clicked in Outlook email when someone else recieves the email?

  25. 25

    How to get name when roll number is given in pandas

  26. 26

    JavaFX how to clear TextField when mouse is clicked on it

  27. 27

    How to hide navbar when clicked ouside of it

  28. 28

    How keep tooltip when is clicked on EditorFor?

  29. 29

    how to open particular fragment when notification is clicked

ホットタグ

アーカイブ