0

i have create a simple file namager with pyqt5 and QTreeView(). W΅hen my path is local folder ...creating ,deleting etc from the app it show it in treeview without problem , example path

C:\Users\USER\Documents\projects\someFile

but when the path is nas server is not show changes example path

\my-ip-add\web\data\someFile

edit: i made create files and folder to update when change made, now trying for delete and drag and drop

in both cases files/folder are deleted ,created . the issue is in nas is not update treeview in delete function and in drag n drop

import os
import sys
from PyQt5.QtWidgets import QTreeView, QFileSystemModel, QApplication, QMenu, QAbstractItemView,QAction, QFileDialog,    QMessageBox
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import options
import shutil

class Tree(QTreeView):
    def __init__(self, path):
        QTreeView.__init__(self)
        self.settings  = options.Settings()
        self.model_base = QFileSystemModel()
        self.path = path
        self.model_base.setRootPath(self.path)
        self.setModel(self.model_base)
        self.setRootIndex(self.model_base.index(self.path))
        self.model_base.setReadOnly(False)

        self.setSelectionMode(self.SingleSelection)
        self.setDragDropMode(QAbstractItemView.InternalMove)
        self.setDragEnabled(True)
        self.setAcceptDrops(True)
        self.setDropIndicatorShown(True)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.open_menu)
        self.doubleClicked.connect(self.OpenFileFromTree)

        
    def dragEnterEvent(self, event):
        m = event.mimeData()
        if m.hasUrls():
            for url in m.urls():
                if url.isLocalFile():
                    event.accept()
                    return
        event.ignore()

    def dropEvent(self, event):
        if event.source():
            QTreeView.dropEvent(self, event)
        else:
            ix = self.indexAt(event.pos())
            if not self.model().isDir(ix):
                ix = ix.parent()
            pathDir = self.model().filePath(ix)
            m = event.mimeData()
            if m.hasUrls():
                urlLocals = [url for url in m.urls() if url.isLocalFile()]
                accepted = False
                for urlLocal in urlLocals:
                    path = urlLocal.toLocalFile()
                    info = QFileInfo(path)
                    n_path = QDir(pathDir).filePath(info.fileName())
                    o_path = info.absoluteFilePath()
                    if n_path == o_path:
                        continue
                    if info.isDir():
                        QDir().rename(o_path, n_path)
                    else:
                        qfile = QFile(o_path)
                        if QFile(n_path).exists():
                            n_path += "(copy)"
                        qfile.rename(n_path)
                    accepted = True
                if accepted:
                    event.acceptProposedAction()

    def open_menu(self):
        menu = QMenu()
        NewFolderAction = QAction('New Folder', self)
        NewFolderAction.triggered.connect(self.create_folder)
        # new file action
        NewFileAction = QAction('New File', self)
        NewFileAction.triggered.connect(self.create_file)
        # delete action
        DeleteAction = QAction('Delete', self)
        DeleteAction.triggered.connect(self.delete_file)
        # rename action
        RenameAction = QAction('Rename', self)

        menu.addAction(NewFolderAction)
        menu.addAction(NewFileAction)
        menu.addAction(DeleteAction)
        menu.exec_(QCursor.pos())

    def delete_file(self):
        # create QMessageBox to ask if the user is sure to delete the file
        box = QMessageBox()
        box.setIcon(QMessageBox.Question)
        box.setWindowTitle('ΠΡΟΣΟΧΗ!')
        box.setText('Are you sure?')
        box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        buttonY = box.button(QMessageBox.Yes)
        buttonY.setText('Yes')
        buttonN = box.button(QMessageBox.No)
        buttonN.setText('Cancel')
        box.exec_()
        if box.clickedButton() == buttonY:
            try:
                index = self.currentIndex()
                file_path = self.model_base.filePath(index)
                if os.path.isfile(file_path):
                    os.remove(file_path)
                    self.model_base.setRootPath(file_path)
                else:
                    # os.rmdir(file_path)
                    shutil.rmtree(file_path, ignore_errors=True)
                    self.model_base.setRootPath(file_path)
            except Exception as e:
                options.SaveLogs('delete_file' + str(e))
                pass

        elif box.clickedButton() == buttonN:
            pass





    def create_file(self):
       index = self.currentIndex()
        file_path = self.model_base.filePath(index)
        file_name = QFileDialog.getSaveFileName(self, "Επιλογή αρχείου", file_path)
        # self.model_base.setRootPath(file_path)
        if file_name[0]:
            with open(file_name[0], 'w') as f:
                new_folder_index = self.model_base.index(file_name[0])
                # Expand the tree view to the new folder
                self.expand(new_folder_index)
                self.setCurrentIndex(new_folder_index)
                pass

    # create a function to open a dialog to create a new folder
    def create_folder(self):
        try:
            global new_folder_path
            index = self.currentIndex()
            if not self.model_base.isDir(index):
                index = index.parent()
            # Get the path of the current index
            path = self.model_base.filePath(index)
            # Create a new folder
            new_folder = QFileDialog.getSaveFileName(self, "Select Folder", path)
            if new_folder[1]:
                new_folder_path = os.path.join(path, new_folder[0])

            QtCore.QDir().mkdir(new_folder_path)
            # Get the index of the new folder
            new_folder_index = self.model_base.index(new_folder_path)
            # Expand the tree view to the new folder
            self.expand(new_folder_index)
            self.setCurrentIndex(new_folder_index)
        except Exception as e:
            options.SaveLogs('create_folder ' + str(e))
            pass

    def OpenFileFromTree(self):
        try:
            index = self.currentIndex()
            file_path = self.model_base.filePath(index)
            self.model_base.setRootPath(file_path)
            p = file_path.replace("//", "\\\\").replace("/", "\\")
            os.startfile(p)
        except Exception as e:
            options.SaveLogs('OpenFileFromTree ' + str(e))
            pass

if __name__ == '__main__':
    app = QApplication(sys.argv)
    tree = Tree(r"\\my-ip\web\data\someFile")
    tree.show()
    sys.exit(app.exec_())
Paris Thiva
  • 1
  • 1
  • 3
  • As the [documentation explains](https://doc.qt.io/qt-5/qfilesystemmodel.html#details), QFileSystemModel "provides access to the **local filesystem**". – musicamante Jan 27 '23 at 14:24
  • Actully i made create functions to work , create file and folder is refresh , i cant find the delete and drag n drop – Paris Thiva Jan 28 '23 at 16:37
  • Please don't change the scope of the question, if your problem is accessing network resources, it's not about drag&drop or deletion. – musicamante Jan 29 '23 at 09:05
  • I dont change any scope. I ask at first place how I can update treeview after a change... So I said I have make to work.. Create file and folder. So if I find a work around for creating maybe can find for deleting and drag n drop as well – Paris Thiva Jan 30 '23 at 12:55
  • Then please try to be more careful when writing questions, as it seemed that your issue was accessing the resources in the first place. So, please clarify what is your actual problem: are you able to delete files or not? are you able to drag & drop or not? Note that the actual operation success and its visible result are related but different aspects: you may be able to delete a file and still see it in the view even if it doesn't exist anymore. – musicamante Jan 30 '23 at 14:23
  • i have updated my question and made it more clear what is the issue – Paris Thiva Feb 02 '23 at 19:08
  • You should always try to use the existing functions the class provides. For instance, instead of deleting with `os.remove()`, use the model's [`remove()`](https://doc.qt.io/qt-5/qfilesystemmodel.html#remove) and [`rmdir()`](https://doc.qt.io/qt-5/qfilesystemmodel.html#rmdir) functions. Also, QFileSystemModel already supports drag and drop of items, and you shouldn't use your own. – musicamante Feb 02 '23 at 20:58
  • i change it to self.model_base.rmdir(index) and self.model_base.remove(index) , same happening . is deleting files in folder but is not updating the treeview – Paris Thiva Feb 03 '23 at 13:53

0 Answers0