Wednesday, March 6, 2024

Upgrading my Simple File List App in Python

 I conceived the notion to enhance the Simple File List App in Python, recognizing its potential utility for other developers. The enhancement introduces a significant improvement: rather than solely presenting a list of files within the selected folder, the application now showcases the contents of each file. This transformation imbues the interface with the familiar appearance and functionality of a file explorer application, augmenting its usability and appeal.

The File List App is a PyQt6-based Python application aimed at providing users with an intuitive interface for browsing and inspecting files within a designated directory. It offers an upgraded user experience compared to traditional file explorers by displaying file contents directly within the application.



Components:

  • QMainWindow: This serves as the main window of the application, providing a framework for organizing various widgets and controls.
  • QTreeView: This widget displays the hierarchical structure of files and directories in a tree-like format, akin to a file explorer. It allows users to navigate through directories and select files of interest.
  • QTextEdit: This widget acts as a text editor, enabling the display of the contents of selected files. It supports read-only mode to prevent accidental modifications to files.
  • QPushButton: This button triggers the action of opening a folder, allowing users to choose the directory they wish to explore.
  • QSplitter: This widget divides the main window into resizable sections, facilitating the adjustment of the size of the tree view and text editor based on user preferences.


Functions:

  • initUI(): This function initializes the user interface by setting up the main window, creating and configuring widgets, and organizing them within layouts.
  • openFolder(): When the "Open Folder" button is clicked, this function prompts the user to select a directory using a file dialog. Upon selection, it updates the window title and calls displayFolderContent() to populate the tree view with the contents of the selected directory.
  • displayFolderContent(folder_path): This function populates the tree view with the contents of the specified folder. It sets up a file system model to represent the directory structure and connects the clicked signal of the tree view to displayFileContent() for displaying file contents.
  • resizeEvent(event): This event handler is triggered when the window is resized. It dynamically adjusts the sizes of the splitter sections to maintain the desired proportions between the tree view and text editor.
  • displayFileContent(index: QModelIndex): This function is called when a file in the tree view is clicked. It retrieves the path of the selected file, reads its contents using utf-8 encoding, and displays the content in the text editor. If an error occurs during file reading, it displays an error message in the text editor.


Conclusion:

The File List App provides an efficient and user-friendly solution for exploring and inspecting files within directories. By seamlessly integrating file browsing and content viewing functionalities, it streamlines the file management process and enhances productivity. With its intuitive interface and robust functionality, it stands as a testament to the power and versatility of Python and PyQt6 in developing rich desktop applications.

Here is the complete program listing:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QFileDialog, QTreeView, QPushButton, QWidget, QTextEdit, QSplitter
from PyQt6.QtGui import QStandardItemModel, QStandardItem, QFileSystemModel
from PyQt6.QtCore import Qt, QDir, QModelIndex

# Global variable to store the folder path
folder_path = ""

class FileListApp(QMainWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.setWindowTitle('File List App')
        self.setGeometry(100, 100, 800, 600)

        # Create widgets
        self.tree_view = QTreeView()
        self.open_button = QPushButton('Open Folder', self)
        self.text_edit = QTextEdit(self)
        self.text_edit.setReadOnly(True)

        # Create a splitter to separate the tree view and the text edit
        self.splitter = QSplitter(Qt.Orientation.Horizontal)
        self.splitter.addWidget(self.tree_view)
        self.splitter.addWidget(self.text_edit)

        # Create layout
        layout = QVBoxLayout()
        layout.addWidget(self.open_button)
        layout.addWidget(self.splitter)

        # Create central widget and set layout
        central_widget = QWidget()
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)

        # Connect the openFolder button to the openFolder slot
        self.open_button.clicked.connect(self.openFolder)

    def openFolder(self):
        global folder_path
        folder_path = QFileDialog.getExistingDirectory(self, 'Open Folder')

        if folder_path:
            self.setWindowTitle(f'File List App - {folder_path}')
            self.displayFolderContent(folder_path)

    def displayFolderContent(self, folder_path):
        # Set up the file system model
        model = QFileSystemModel()
        model.setRootPath(folder_path)
        model.setFilter(QDir.Filter.NoDotAndDotDot | QDir.Filter.AllEntries)

        # Set the model to the tree view
        self.tree_view.setModel(model)
        self.tree_view.setRootIndex(model.index(folder_path))
        self.tree_view.setColumnWidth(0, 250)  # Adjust column width

        # Connect itemClicked signal to displayFileContent
        self.tree_view.clicked.connect(self.displayFileContent)

        # Adjust the sizes of the splitter
        self.splitter.setSizes([self.width() * 0.3, self.width() * 0.7])

    def resizeEvent(self, event):
        super().resizeEvent(event)
        # Update splitter sizes when window is resized
        self.splitter.setSizes([self.width() * 0.3, self.width() * 0.7])

    def displayFileContent(self, index: QModelIndex):
        global folder_path
        # Get the file path from the selected index
        file_path = self.tree_view.model().filePath(index)

        # Read the content of the file using utf-8 encoding
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                content = file.read()
                self.text_edit.setText(content)
        except Exception as e:
            self.text_edit.setText(f"Error reading file: {str(e)}")

def main():
    app = QApplication(sys.argv)
    window = FileListApp()
    window.show()
    sys.exit(app.exec())

if __name__ == '__main__':
    main()

No comments:

Post a Comment