from PyQt5.QtWidgets import QAction, QApplication, QMainWindow class MyWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): action = QAction('Print message', self) action.triggered.connect(lambda: print('Hello, World!')) self.addAction(action) app = QApplication([]) window = MyWindow() window.show() app.exec_()
from PyQt5.QtWidgets import QAction, QApplication, QMainWindow, QFileDialog class MyWindow(QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): action = QAction('Open file', self) action.triggered.connect(self.openFileDialog) self.addAction(action) def openFileDialog(self): filename = QFileDialog.getOpenFileName(self, 'Open file', '/') if filename[0]: print(f'Opening file {filename[0]}') app = QApplication([]) window = MyWindow() window.show() app.exec_()This code creates a new QAction instance with the label 'Open file' and connects it to the `openFileDialog()` function. The `QFileDialog` class is used to display a file dialog window where the user can select a file. The selected file name will be printed to the console.