为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用PYQT5在QTreeView中选择和编辑新创建的文件夹

如何使用PYQT5在QTreeView中选择和编辑新创建的文件夹

天涯尽头无女友 2021-05-14 17:28:59
我试图弄清楚如何选择和编辑新创建的文件夹。这是一些代码来演示它:import osimport sysfrom PyQt5.QtWidgets import (QApplication,                             QMainWindow,                             QLabel,                             QLineEdit,                             QPushButton,                             QShortcut,                             QFileSystemModel,                             QTreeView,                             QWidget,                             QVBoxLayout,                             QHBoxLayout,                             QLayout,                             QMenu,                             QPlainTextEdit,                             QSizePolicy,                             QMessageBox,                             QAbstractItemView)from PyQt5.QtCore import QSize, Qt, QRectfrom PyQt5.QtGui import QKeySequenceclass FSView(QWidget):    def __init__(self):        super().__init__()        self.initUI()    def initUI(self):        self.setFixedSize(size.width()*1/4, size.height()*0.85)        self.model = QFileSystemModel()        self.model.setRootPath('')        self.model.setReadOnly(False)        self.tree = QTreeView()        self.tree.setContextMenuPolicy(Qt.CustomContextMenu)        self.tree.customContextMenuRequested.connect(self.openMenu)        self.tree.setModel(self.model)        self.tree.setAnimated(False)        self.tree.setIndentation(20)        self.tree.setDragDropMode(QAbstractItemView.InternalMove)        windowLayout = QVBoxLayout()        windowLayout.addWidget(self.tree)        self.setLayout(windowLayout)    def openMenu(self, position):        menu = QMenu()        menu.addAction('New folder', self.NewF)        menu.exec_(self.tree.viewport().mapToGlobal(position))创建新文件夹后,我希望同时选择它并使其处于编辑模式(即:self.tree.edit(correctIndex))。我已经检查了一些帖子(在这里),但仍然没有设法获得正确的索引。
查看完整描述

1 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超3个赞

使用您的代码,您必须首先获取将路径传递给它的QModelIndexusingindex()方法QFileSystemModel,然后调用QTreeView的setCurrentIndex()andedit()方法。


def NewF(self):

    d = str(self.model.filePath(self.tree.currentIndex())) + '/New folder'

    if not os.path.exists(d):

        os.mkdir(d)

    ix = self.model.index(d)

    QTimer.singleShot(0, lambda ix=ix: self.tree.setCurrentIndex(ix))

    QTimer.singleShot(0, lambda ix=ix: self.tree.edit(ix))

或使用如下所示的mkdir()方法QFileSystemModel:


def NewF(self):

    ci = self.tree.currentIndex()

    ix = self.model.mkdir(ci, "New folder")

    QTimer.singleShot(0, lambda ix=ix : self.tree.setCurrentIndex(ix))

    QTimer.singleShot(0, lambda ix=ix : self.tree.edit(ix))


查看完整回答
反对 回复 2021-05-25
  • 1 回答
  • 0 关注
  • 178 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号