# coding: utf-8
import sys
import traceback
import os
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *


class FileDialog(QDialog):
    """文件管理Demo"""
    def __init__(self, parent=None):
        super(FileDialog, self).__init__(parent)

        self.init_ui()
        self.init_slot()

    def init_ui(self):
        """初始化UI"""
        try:
            self.resize(720, 480)
            self.setWindowTitle("文件管理Demo")

            # 根路径
            root_path = os.path.expanduser("~")

            # 文件夹数据
            self.file_model = QFileSystemModel()
            self.file_model.setRootPath(root_path)

            # 树形控件
            self.treeView = QTreeView(self)
            self.treeView.setModel(self.file_model)
            self.treeView.setRootIndex(self.file_model.index(root_path))
            # self.treeView.setColumnHidden(1, True)
            # self.treeView.setColumnHidden(2, True)
            # self.treeView.setColumnHidden(3, True)
            self.treeView.header().setSectionResizeMode(QHeaderView.Stretch)
            # 布局
            layout = QHBoxLayout()
            layout.addWidget(self.treeView)
            self.setLayout(layout)
        except:
            traceback.print_exc()

    def init_slot(self):
        """初始化信号"""
        try:
            self.treeView.clicked.connect(self.select_file_event)  # 选中某一项
        except:
            traceback.print_exc()

    def select_file_event(self):
        """选中某一项"""
        try:
            currentIndex = self.treeView.currentIndex()
            file_path = self.file_model.filePath(currentIndex)
            print(file_path)
        except:
            traceback.print_exc()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    file_dialog = FileDialog()
    file_dialog.show()
    sys.exit(app.exec_())
