2

I have bound a QFileSystemModel to a QTreeView. How can I hide the file extensions keeping the rename functional ? Meanwhile hide extension in the rename mode to avoid a wrong extension

Thanks

my code as below:

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import * 
class FileTree(QWidget): 
    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 file system view'
        self.initUI()     
    def initUI(self):
        self.setWindowTitle(self.title)
        self.model = QFileSystemModel()
        self.model.setRootPath('')
        self.model.setReadOnly(False)        
        
        self.tree = QTreeView()        
        self.tree.setModel(self.model)
        self.tree.setColumnWidth(0,300)         
        self.tree.setAnimated(False)
        self.tree.setIndentation(20)
        self.tree.setSortingEnabled(True)

        self.tree.setColumnHidden(1,True)
        self.tree.setColumnHidden(2,True)
        self.tree.setColumnHidden(3,True)
        self.model.sort(0,Qt.AscendingOrder)

        self.tree.setWindowTitle("Dir View")
        self.tree.resize(640, 480)         
        self.windowLayout = QVBoxLayout()
        self.windowLayout.addWidget(self.tree)
        self.windowLayout.setContentsMargins(0,0,0,0)
        self.setLayout(self.windowLayout)
        self.setContentsMargins(0,0,0,0)

        self.show() 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = FileTree()
    sys.exit(app.exec_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Mike
  • 37
  • 4

1 Answers1

2

The solution is to use a delegate:

class NameDelegate(QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        if isinstance(index.model(), QFileSystemModel):
            if not index.model().isDir(index):
                option.text = index.model().fileInfo(index).baseName()

    def setEditorData(self, editor, index):
        if isinstance(index.model(), QFileSystemModel):
            if not index.model().isDir(index):
                editor.setText(index.model().fileInfo(index).baseName())
            else:
                super().setEditorData(editor, index)

    def setModelData(self, editor, model, index):
        if isinstance(model, QFileSystemModel):
            fi = model.fileInfo(index)
            if not model.isDir(index):
                model.setData(index, editor.text() + "." + fi.suffix())
            else:
                super().setModelData(editor, model.index)
delegate = NameDelegate(self.tree)
self.tree.setItemDelegate(delegate)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Thank you, I have tried your code, it works fine in normal mode but the file extension shows again when try to rename the file,it can't avoid rename to other extension. – Mike Jul 02 '20 at 15:13