【问题标题】:how to hide file extensions on a QFileSystemModel如何隐藏 QFileSystemModel 上的文件扩展名
【发布时间】:2020-07-02 23:52:51
【问题描述】:

我已将 QFileSystemModel 绑定到 QTreeView。 如何隐藏保持重命名功能的文件扩展名?同时在重命名模式下隐藏扩展名,避免扩展名错误

谢谢

我的代码如下:

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_())

【问题讨论】:

    标签: python pyqt pyqt5 qfilesystemmodel


    【解决方案1】:

    解决方案是使用委托:

    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)
    

    【讨论】:

    • 谢谢,我试过你的代码,在正常模式下可以正常工作,但是尝试重命名文件时文件扩展名再次显示,无法避免重命名为其他扩展名。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 2014-02-24
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    相关资源
    最近更新 更多