Stack Overflow Asked on November 29, 2021
I am trying to drag and drop a folder into a a QTreeWidget and it will print out all the files in that folder and any other folder structures under that. I am very unfamiliar with QTreeWidget and in my example I was just trying to add data under the ‘Name’ column everything I tried i got different errors from model is a private method
to argument 1 has unexpected type 'Tree'
. How can I add data under each column?
import os
from PyQt5.QtWidgets import QFileSystemModel, QApplication, QAbstractItemView,
QMainWindow, QPushButton, QTreeWidget, QTreeWidgetItem
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class Tree(QTreeWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setAcceptDrops(True)
self.resize(600, 600)
self.setHeaderLabels(['Name', 'Size', 'Upload Status'])
model = QFileSystemModel()
model.setRootPath(QDir.currentPath())
model.setReadOnly(False)
self.setSelectionMode(self.SingleSelection)
self.setDragDropMode(QAbstractItemView.InternalMove)
self.setDragEnabled(True)
self.setAcceptDrops(True)
self.setDropIndicatorShown(True)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(Qt.CopyAction)
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(Qt.CopyAction)
event.accept()
for url in event.mimeData().urls():
if url.isLocalFile():
rootPath = url.toString()[8:]
if os.path.isfile(rootPath):
address = rootPath
item = QTreeWidgetItem()
item.setData(self, 0, 0, address)
self.addItem(item)
else:
for path, subdirs, files in os.walk(rootPath):
for file in files:
address = str(url.toLocalFile())
path = path.replace("\", "/")
directory_name = path.replace(rootPath, "")
displayName = directory_name + '/' + file
address += displayName
item = QTreeWidgetItem()
item.setData(self, 0, 0, address)
self.addItem(item)
else:
event.ignore()
class Main(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('Login Form')
self.resize(1200, 600)
self.treeBox = Tree(self)
self.btn = QPushButton('Upload', self)
self.btn.setGeometry(850, 400, 200, 50)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = Main()
w.show()
sys.exit(app.exec_())
For example if I drop a folder that contains file1, file2, subfolder, and subfolder2 the treewidget will display the root folder with each file as a child. Along with the subfolders in the root will also display their children(files inside the subfolder).
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP