import sys from PyQt6.QtWidgets import ( QApplication, QMainWindow, QWidget, QPlainTextEdit, QVBoxLayout, QFileDialog, QMessageBox, QMenuBar, QMenu, QToolBar ) from PyQt6.QtGui import QAction, QKeySequence from PyQt6.QtCore import Qt class TextViewer(QMainWindow): def __init__(self): super().__init__() self.initializeUI() def initializeUI(self): # Set window properties self.setGeometry(100, 100, 600, 400) # Position and size self.setWindowTitle("Accessible Text Viewer") # Create the menu bar self.menu_bar = self.menuBar() self.menu = QMenu("Menu", self) self.menu.setTitle("Menu (&M)") self.menu_bar.addMenu(self.menu) # Create actions for the menu self.open_file_action = QAction("Open File", self) self.open_file_action.setShortcut(QKeySequence("Alt+O")) self.open_file_action.triggered.connect(self.open_file) self.menu.addAction(self.open_file_action) # Create the toolbar self.toolbar = QToolBar("Main Toolbar", self) self.addToolBar(self.toolbar) # Add actions to the toolbar self.toolbar.addAction(self.open_file_action) # Create the plain text editor self.text_viewer = QPlainTextEdit(self) self.text_viewer.setReadOnly(True) # Make the text editor read-only self.text_viewer.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByKeyboard | Qt.TextInteractionFlag.TextSelectableByMouse) self.text_viewer.setAccessibleName("Text Viewer") # Set up the layout central_widget = QWidget() layout = QVBoxLayout(central_widget) layout.setMenuBar(self.menu_bar) layout.addWidget(self.text_viewer) self.setCentralWidget(central_widget) # Show the window self.show() def open_file(self): # Open file dialog to select a file file_name, _ = QFileDialog.getOpenFileName( self, "Open Text File", "", "Text Files (*.txt);;All Files (*)" ) if file_name: try: with open(file_name, 'r', encoding='utf-8') as file: content = file.read() self.text_viewer.setPlainText(content) # Display file content in plain text editor self.text_viewer.setFocus() except Exception as e: # Display error message if file reading fails error_message = f"Error reading file:\n{e}" self.text_viewer.setPlainText(error_message) QMessageBox.critical(self, "File Read Error", error_message) if __name__ == "__main__": app = QApplication(sys.argv) window = TextViewer() sys.exit(app.exec())