Search code examples
pythonpyqtpyqt5file-browser

MouseClick Event on PyQt Folder Tree


I have coded out a small application using PyQt5. The application gives a tree view of all folders in the computer plus a lineEditd where the user can type things:

import sys
from PyQt5.QtWidgets import (
    QMainWindow, QApplication,
    QHBoxLayout,QWidget,
     QVBoxLayout,QFileSystemModel, QTreeView, QLineEdit
)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        layout = QHBoxLayout()
        application = App()
        layout.addWidget(application)
        widget = QWidget()
        widget.setLayout(layout)
        self.setCentralWidget(widget)
    
        

class App(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    
    def initUI(self):
        self.model = QFileSystemModel()
        self.model.setNameFilters([''])
        self.model.setNameFilterDisables(0)
        self.model.setRootPath('')
        self.tree = QTreeView()
        self.tree.setModel(self.model)
        
        self.tree.setAnimated(False)
        self.tree.setSortingEnabled(True)
        layout = QVBoxLayout()
        layout.addWidget(self.tree)
        self.input = QLineEdit()
        layout.addWidget(self.input)
        self.setLayout(layout)
        self.show()

app = QApplication(sys.argv)
w = MainWindow()
w.show()
app.exec()

My next goal is to make my application able to detect mouse click on the tree diagram. More precisely, in an event of a mouse click on any folder in the tree, I want to know the directory of the folder which the user clicks (so that I can, for instance, update the LineEdit by filling it with the directory)

To achieve such a goal, the first thing I need to do is to make mouse click in the tree an event. If I add a method like:

def mouseMoveEvent(self, e):
    #some code

It will not give me an event reflecting the fact that the mouse click happens in the tree. I am therefore stuck on even making mouse click in tree an event, nor to mention reading the directory .

Edit:

By writing

self.tree.clicked

I am able to detect any click in the tree. However, I still do not know how to get the directory.


Solution

  • If you want to get the directory using the view's clicked signal then you should use the model:

    self.tree.clicked.connect(self.handle_clicked)
    
    def handle_clicked(self, index):
        filename = self.model.fileName(index)
        path = self.model.filePath(index)
        fileinfo = self.model.fileInfo(index)
        print(filename, path, fileinfo)