📜  PyQt5 – QAction(1)

📅  最后修改于: 2023-12-03 15:03:59.564000             🧑  作者: Mango

PyQt5 – QAction

PyQt5 is a Python module that allows for the development of cross-platform graphical user interfaces using the Qt framework. One of the main components of any GUI application is the ability to provide actions for the user, such as opening or saving files, copy or paste, or creating new items. In PyQt5, these actions are implemented using the QAction class.

Creating a QAction Object

To create a new QAction object, we first need to import the necessary modules:

from PyQt5.QtWidgets import QAction
from PyQt5.QtGui import QIcon

The QAction constructor accepts several arguments, including the text that will be displayed in the menu or toolbar, an optional icon, a shortcut key sequence, and a parent widget. For example, here is a basic QAction object with just a text label:

my_action = QAction("My Action")

We can also add an icon to the action:

my_action = QAction(QIcon("my_icon.png"), "My Action")

Finally, we can specify a keyboard shortcut for the action:

my_action = QAction(QIcon("my_icon.png"), "My Action", self)
my_action.setShortcut("Ctrl+S")
Adding QAction to a Menu or Toolbar

Once we have created our QAction object, we need to add it to a menu or toolbar for the user to interact with. To add the action to a menu, we first create a new QAction object and add it to the menu using the addAction method:

my_menu = QMenu("File")
my_action = QAction(QIcon("my_icon.png"), "Save", self)
my_menu.addAction(my_action)

We can also add the action to a toolbar using the addAction method of the QToolBar class:

my_toolbar = QToolBar("Main Toolbar")
my_action = QAction(QIcon("my_icon.png"), "Save", self)
my_toolbar.addAction(my_action)
Connecting a QAction to a Function

To make our QAction actually do something when it is activated, we need to connect it to a function using the triggered signal. Here is an example of how to connect a QAction to a function:

my_action.triggered.connect(self.save_file)

In this example, we are connecting the triggered signal of our QAction to a function called save_file. When the QAction is activated (e.g. when the user clicks on it or presses the keyboard shortcut), the save_file function will be called.

Conclusion

In this brief introduction to QAction in PyQt5, we have seen how to create a new QAction object, add it to a menu or toolbar, and connect it to a function that will be executed when it is activated. With these basic concepts, you can start building your own powerful GUI applications with PyQt5.