简体   繁体   English

PyQt 文件夹树上的 MouseClick 事件

[英]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:我使用 PyQt5 编写了一个小应用程序。该应用程序提供了计算机中所有文件夹的树视图以及用户可以键入内容的 lineEditd:

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)更准确地说,如果鼠标单击树中的任何文件夹,我想知道用户单击的文件夹的目录(例如,我可以通过用目录填充它来更新 LineEdit)

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.但是,我仍然不知道如何获取目录。

If you want to get the directory using the view's clicked signal then you should use the model:如果您想使用视图的点击信号获取目录,那么您应该使用 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM