I am trying to figure out how to select and edit newly created folder. Here is a bit of code demonstrating it:
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))
def NewF(self):
d = str(self.model.filePath(self.tree.currentIndex())) + '/New folder'
if not os.path.exists(d):
os.mkdir(d)
# correctIndex = self.tree.currentIndex() + 1 #not working
# self.tree.edit(correctIndex)
if __name__ == '__main__':
app = QApplication(sys.argv)
screen = app.primaryScreen()
size = screen.size()
ex = FSView()
ex.show()
sys.exit(app.exec_())
After creating the new folder, I would like it to be selected and in edit mode at same time (i.e.: self.tree.edit(correctIndex)).
I have checked some posts (here) but still have not managed to get the correct index.
Thanks for suggestions.
Using your code you must first obtain the QModelIndex
using the index()
method of QFileSystemModel
passing it the path, and then call the setCurrentIndex()
and edit()
methods of QTreeView.
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))
Or use the mkdir()
method of QFileSystemModel
as shown below:
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))