[파이썬] PyQt 상세 뷰 (`QDetailView`)

In PyQt, the QDetailView widget is used to display a hierarchical model in a detailed view. It provides a user-friendly interface to view and edit the data in a structured manner. This widget is perfect for displaying complex data models with multiple levels of hierarchy.

Installation

To use QDetailView in your PyQt application, you need to have PyQt installed. You can install PyQt using pip:

pip install PyQt5

Alternatively, you can install it using conda:

conda install pyqt

Example usage

Let’s create a simple example to demonstrate the usage of QDetailView.

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QTreeView, QStandardItemModel, QDetailView

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.setWindowTitle("QDetailView Example")
        self.setGeometry(100, 100, 600, 400)

        tree_view = QTreeView(self)
        detail_view = QDetailView(self)

        # Create a hierarchical model
        model = QStandardItemModel()
        parent_item = model.invisibleRootItem()

        # Add items to the model
        item1 = QStandardItem("Item 1")
        item1.setText("Name", "John")
        item1.setText("Age", "25")
        parent_item.appendRow(item1)

        item2 = QStandardItem("Item 2")
        item2.setText("Name", "Jane")
        item2.setText("Age", "30")
        parent_item.appendRow(item2)

        item3 = QStandardItem("Item 3")
        item3.setText("Name", "Bob")
        item3.setText("Age", "35")
        parent_item.appendRow(item3)

        # Set the model for tree and detail view
        tree_view.setModel(model)
        detail_view.setModel(model)

        # Set the current index of the tree view to show the first item
        tree_view.setCurrentIndex(model.index(0, 0))

        self.setCentralWidget(tree_view)
        self.addDockWidget(Qt.RightDockWidgetArea, detail_view)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())

In this example, we create a MainWindow class that inherits from QMainWindow. We create a QTreeView widget to display the hierarchical data model and a QDetailView widget to display the details of the selected item. We use a QStandardItemModel to create the hierarchical model and populate it with some sample data.

When an item is selected in the QTreeView, its details are shown in the QDetailView. The docked QDetailView updates automatically as the selection changes in the QTreeView.

Summary

The QDetailView widget in PyQt is a useful tool for displaying and editing hierarchical models in a user-friendly manner. It provides a detailed view of the selected item and allows easy navigation through the hierarchy. By using this widget, you can enhance the user experience of your PyQt applications.