I have a question.
I'm using PyQt5 and Python 3.6, and I'm looking to use a QTreeview for listing files in a folder. When a user right-clicks a file in the folder, I'll have a context menu. One of the options will be Rename. If the user clicks that, I want the file to be selected and then the file's name highlighted, like Windows does when you do this in File Explorer.
Windows File Rename
I'm pretty sure I've figured out how I want to approach the menu itself and the other functions (Delete, Open, etc.) And I'm fairly certain I'll be able to use a slot/signal to capture the new name and change it in the file system. But I'm COMPLETELY stumped on how to do this selection and highlighting programmatically. Again, this will be done via a context menu function. I've spent HOURS now scouring the Internet and Qt documentation trying to figure this out. I admit I have gotten pretty lost in the documentation on this one.
I've seen where you can use a QTreeview's currentIndex() to get the QModelIndex object of the currently selected item, but digging through the QModelIndex documentation, I haven't found anything about editing or highlighting items. I know there are flags. I see them in examples of models. I don't see what you're supposed to do with them.
Does QTreeview support this functionality? I've also looked at QTreewidget, but it doesn't seem like it has the features I need to display files as nodes file system style.
Thanks for any help.
What you have to do is the following:
QFileSystemModel
.indexAt()
edit()
method of the QTreeView
.In the example I show how to enable the context menu in the first column.
from PyQt5 import QtCore, QtWidgets
class FileSystemView(QtWidgets.QTreeView):
def __init__(self, parent=None):
super(FileSystemView, self).__init__(parent)
self.model = QtWidgets.QFileSystemModel()
self.model.setRootPath(QtCore.QDir.homePath())
self.setModel(self.model)
self.setRootIndex(self.model.index(QtCore.QDir.homePath()))
self.model.setReadOnly(False)
self.setAnimated(False)
self.setSortingEnabled(True)
self.setEditTriggers(QtWidgets.QTreeView.NoEditTriggers)
self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.showContextMenu)
def showContextMenu(self, point):
ix = self.indexAt(point)
if ix.column() == 0:
menu = QtWidgets.QMenu()
menu.addAction("Rename")
action = menu.exec_(self.mapToGlobal(point))
if action:
if action.text() == "Rename":
self.edit(ix)
if __name__ == '__main__':
import sys
app =QtWidgets.QApplication(sys.argv)
w = FileSystemView()
w.show()
sys.exit(app.exec_())