猿问

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

我试图弄清楚如何选择和编辑新创建的文件夹。这是一些代码来演示它:


import os

import sys

from 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, QRect

from PyQt5.QtGui import QKeySequence


class 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))。


我已经检查了一些帖子(在这里),但仍然没有设法获得正确的索引。


天涯尽头无女友
浏览 179回答 1
1回答

一只名叫tom的猫

使用您的代码,您必须首先获取将路径传递给它的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))
随时随地看视频慕课网APP

相关分类

Python
我要回答