0

Нужна помощь, Нужно что бы по нажатию на файл в TreeView создавался путь к файлу и записывался в переменную. Так же что бы был мультивыбор. То-есть пользователь выбрал несколько файлов сразу и нажал кнопку PushButton и выбранные файлы сохранились в определённую директорию.

Пример кода ниже

from PySide2 import QtCore, QtGui, QtWidgets   

import os

file = 'template'
path_dir = r'D:\templates'

class Ui_Form(object):

    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(1266, 798)
        self.treeView = QtWidgets.QTreeView(Form)
        self.treeView.setGeometry(QtCore.QRect(40, 70, 611, 241))
        self.treeView.setObjectName("treeView")
        #-------------
# ?     self.treeView.QFileSystemModel.directoryLoaded('D:\test\qt')
        #-------------
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(670, 70, 131, 41))
        self.pushButton.setObjectName("pushButton")
        self.pushButton.clicked.connect(self.save_file)

        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(40, 42, 541, 21))
        self.label.setObjectName("label")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(QtWidgets.QApplication.translate("Form", "Form", None, -1))
        self.pushButton.setText(QtWidgets.QApplication.translate("Form", "PushButton", None, -1))
        self.label.setText(QtWidgets.QApplication.translate("Form", "TextLabel", None, -1))

    def save_file(self):
        print('File', file , 'saved in: ' , path_dir, '!')


class Widget(QtWidgets.QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        self.setupUi(self)

        self.resize(1266, 798)
        layout = QtWidgets.QHBoxLayout(self)
        # layout.addWidget(self.label)
        # layout.addWidget(self.treeView)
        # layout.addWidget(self.pushButton)
        self.model = QtWidgets.QFileSystemModel()
        self.model.setFilter(QtCore.QDir.AllEntries | QtCore.QDir.Hidden | QtCore.QDir.NoDot)
        self.path = os.path.expanduser('D:')                          # <-- ('D:/test/qt')
        self.parentIndex  = self.model.setRootPath(self.path)
        self.treeView.setModel(self.model)
        self.treeView.setRootIndex(self.model.index(self.path))
        self.model.directoryLoaded.connect(self._loaded)

        self.dirictory = QtWidgets.QDirModel()
        self.dirictory.index(self.path)
        self.dirictory.filePath(self.dirictory.index(self.path))
        print(self.dirictory.filePath(self.dirictory.index(self.path)))



    def _loaded(self, path):
        print('_loaded', self.path) 
        print('++loaded', self.dirictory.filePath(self.dirictory.index(self.path)))


if __name__ == "__main__":
   import sys
   app = QtWidgets.QApplication(sys.argv)
#   Form = QtWidgets.QWidget()
#   ui = Ui_Form()
#   ui.setupUi(Form)
#   Form.show()
   w = Widget()
   w.show()
   sys.exit(app.exec_())

1 ответ 1

0

Sorry, без вашего дизайна и на PyQt5

import sys
import os
import shutil

#from PySide2 import QtCore, QtGui, QtWidgets  
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Widget(QWidget):
    def __init__(self):
        super().__init__()

        self.treeview = QTreeView()

        self.listview = QListView()
        # Это свойство определяет, может ли пользователь выбрать один или несколько элементов... 
        self.listview.setSelectionMode(QListView.ExtendedSelection)


        self.btn = QPushButton("Сохранить выбранные файлы в в определённую директорию.")
        self.btn.clicked.connect(self._on_btn_clicked)
        self.label = QLabel()

        lay = QGridLayout(self)         
        lay.addWidget(self.treeview, 0, 0)
        lay.addWidget(self.listview, 0, 1)
        lay.addWidget(self.label,    1, 0)
        lay.addWidget(self.btn,      1, 1)

        # установить нужный каталог
        #path = QDir.rootPath()
        #path = QDir.currentPath()
        path = "D:/_Qt/"

        # --- dirModel ---
        self.dirModel = QFileSystemModel()
        # setRootPath Устанавливает каталог, который просматривается моделью в newPath, 
        # путем установки на нее наблюдателя файловой системы.
        #self.dirModel.setRootPath(QDir.rootPath())
        self.dirModel.setRootPath(QDir.currentPath())
        self.dirModel.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs)

        # --- fileModel ---
        self.fileModel = QFileSystemModel()
        self.fileModel.setFilter(QDir.NoDotAndDotDot |  QDir.Files)

        self.treeview.setModel(self.dirModel)
        self.listview.setModel(self.fileModel)

        self.treeview.setRootIndex(self.dirModel.index(path))
        self.listview.setRootIndex(self.fileModel.index(path))

        self.treeview.clicked.connect(self.on_clicked)

    def on_clicked(self, index):
        path = self.dirModel.fileInfo(index).absoluteFilePath()
        self.listview.setRootIndex(self.fileModel.setRootPath(path))

    def _on_btn_clicked(self):
        listPath = self.listview.selectionModel().selectedIndexes()
        if not listPath: return False

        dirPath = QFileDialog.getExistingDirectory(self,"Выбрать папку для копирования.",".")
        if not dirPath: return False
        self.label.setText("Выбрали папку: <b>{}</b>".format(dirPath))

        for row in self.listview.selectionModel().selectedIndexes():
            path = self.fileModel.filePath(row)
            if os.path.isfile(path):
                shutil.copy(path, dirPath)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w   = Widget()
    w.show()
    sys.exit(app.exec_())

введите сюда описание изображения

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.