def __init__(self):
        super().__init__()

        self.setWindowTitle('Drag & Drop')

        # Даем разрешение на Drop
        self.setAcceptDrops(True)

        self.list_files = QListWidget()
        self.label_total_files = QLabel()

        model = QFileSystemModel()
        model.setRootPath(QDir.currentPath())
        model.setReadOnly(False)

        self.tree = QTreeView()
        self.tree.setModel(model)
        self.tree.setRootIndex(model.index(QDir.currentPath()))
        self.tree.setSelectionMode(QTreeView.SingleSelection)
        self.tree.setDragDropMode(QTreeView.InternalMove)

        main_layout = QVBoxLayout()
        main_layout.addWidget(self.tree)
        main_layout.addWidget(QLabel('Перетащите файл:'))
        main_layout.addWidget(self.list_files)
        main_layout.addWidget(self.label_total_files)

        central_widget = QWidget()
        central_widget.setLayout(main_layout)

        self.setCentralWidget(central_widget)

        self._update_states()
示例#2
0
class ProtocolFileViewer(QTreeView):
    def __init__(self, folder, parent=None):
        super(ProtocolFileViewer, self).__init__()
        self.parent = parent
        self.fs_model = QFileSystemModel(self)
        self.fs_model.setReadOnly(True)
        self.setModel(self.fs_model)
        self.folder = folder
        self.setRootIndex(self.fs_model.setRootPath(folder))
        self.setAlternatingRowColors(True)
        self.setSelectionMode(3)
        #         self.setDragEnabled(True)
        #         self.setAcceptDrops(True)
        #         self.setDragDropMode(QAbstractItemView.DragDrop)
        #         self.setDropIndicatorShown(True)
        #         #[self.hideColumn(i) for i in range(1,4)]
        self.setColumnWidth(0, self.width() * .3)

        def query_root(self):
            folder = QFileDialog().getExistingDirectory(
                self, "Select directory", os.path.curdir)
            self.setRootIndex(self.fs_model.setRootPath(folder))
            self.expandAll()
            self.folder = folder
            if hasattr(self.parent, 'folder'):
                self.parent.folder.setText('{0}'.format(folder))
示例#3
0
class App(QWidget):

    def __init__(self):
        print("xx")
        #QMainWindow.__init__(self)
        super(App,self).__init__()
        #QtWidgets.QWidget.__init__(self)
        self.title = 'select file'
        self.left = 10
        self.top = 10
        self.width = 640
        self.height = 480
        self.initUI()
    
    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        
        self.model = QFileSystemModel()
        self.model.setRootPath('')
        self.tree = QTreeView()
        self.tree.clicked.connect(self.onClicked)
        self.tree.setModel(self.model)
        self.fileSystemModel = QFileSystemModel(self.tree)
        self.fileSystemModel.setReadOnly(True)
        self.fileSystemModel.setRootPath('')
        
        self.tree.setAnimated(False)
        self.tree.setIndentation(20)
        self.tree.setSortingEnabled(True)
        
        self.tree.setWindowTitle("Dir View")
        self.tree.resize(640, 480)
        
        windowLayout = QVBoxLayout()
        windowLayout.addWidget(self.tree)
        self.setLayout(windowLayout)
        self.show()
    def onClicked(self, index):
        global path
        path = self.sender().model().filePath(index)
        #path1=self.sender().model().filePath()
        print(path)
        self.close()
        Ui_MainWindow.display1(self)
示例#4
0
	def __init__(self):
		QTreeView.__init__(self)
		model = QFileSystemModel()
		model.setRootPath(QDir.homePath())

		self.setModel(model)
		self.setRootIndex(model.index(QDir.homePath()))
		model.setReadOnly(False)

		for i in range(1, model.columnCount()):
			self.hideColumn(i)
		self.setHeaderHidden(True)	
		
		self.setSelectionMode(self.SingleSelection)
		self.setDragDropMode(QAbstractItemView.InternalMove)
		self.setDragEnabled(True)
		self.setAcceptDrops(True)
		self.setDropIndicatorShown(True)
示例#5
0
class AssetBrowser(QMainWindow, Ui_MainWindow):
    asset_clicked = pyqtSignal(str, str, name='assetClicked')

    def __init__(self):
        super(AssetBrowser, self).__init__()
        self.setupUi(self)

        self.dir_model = QFileSystemModel()
        self.dir_model.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs)
        self.dir_model.setReadOnly(False)

        self.dir_view.setModel(self.dir_model)
        self.dir_view.hideColumn(1)
        self.dir_view.hideColumn(2)
        self.dir_view.hideColumn(3)

        self.file_model = QFileSystemModel()
        self.file_model.setFilter(QDir.NoDotAndDotDot | QDir.Files)
        self.file_model.setReadOnly(False)

        self.file_view.setModel(self.file_model)

    def open_project(self, project_dir):
        path = os.path.join(project_dir)

        self.dir_model.setRootPath(path)
        self.file_model.setRootPath(path)

        self.dir_view.setRootIndex(self.dir_model.index(path))
        self.file_view.setRootIndex(self.file_model.index(path))

    def dir_clicked(self, idx):
        path = self.dir_model.fileInfo(idx).absoluteFilePath()

        self.file_view.setRootIndex(self.file_model.setRootPath(path))

    def file_doubleclicked(self, idx):
        fileinfo = self.file_model.fileInfo(idx)

        path = fileinfo.absoluteFilePath()
        ext = fileinfo.suffix()

        self.asset_clicked.emit(path, ext)
示例#6
0
    def browserFile(self):

        global Browser, Model

        self.browser = QTreeView()

        model = QFileSystemModel()
        model.setNameFilters(['*.nii'])
        model.setNameFilterDisables(False)
        model.setReadOnly(True)

        self.browser.setModel(model)
        self.browser.expandAll()
        self.browser.setColumnWidth(0, 400)

        self.browser.selectionModel().selectionChanged.connect(self.select)

        Browser = self.browser
        Model = model
示例#7
0
class view(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setGeometry(0, 0, 800, 600)
        self.model = QFileSystemModel()
        self.model.setReadOnly(False)
        self.model.setRootPath("")
        self.tree = QTreeView()
        self.tree.setModel(self.model)
        self.tree.setAnimated(True)
        self.tree.setIndentation(10)
        self.tree.setSortingEnabled(True)
        self.tree.setWindowTitle("Dir View")
        self.tree.resize(640, 480)
        windowLayout = QVBoxLayout()
        windowLayout.addWidget(self.tree)
        self.setLayout(windowLayout)
        self.show()
示例#8
0
    def dormant(self):

        treeView = QTreeView()

        treeView.setContextMenuPolicy(Qt.CustomContextMenu)
        treeView.customContextMenuRequested.connect(self.tabMenu)

        fileSystemModel = QFileSystemModel(treeView)
        fileSystemModel.setReadOnly(False)
        self.dormant_path = expanduser('~') + '\Documents'
        root = fileSystemModel.setRootPath(self.dormant_path)
        treeView.setModel(fileSystemModel)
        treeView.setRootIndex(root)
        treeView.setSortingEnabled(True)

        treeView.clicked.connect(self.on_clicked)

        dormant_clearAll_button = QPushButton("Clear all Files")
        dormant_clearAll_button.setFixedSize(90, 30)
        self.dormant_delete_button = QPushButton('Delete')
        self.dormant_delete_button.setFixedSize(90, 30)

        self.dormant_delete_button.clicked.connect(self.delete_file)

        dormant_zip_button = QPushButton('Zip file')
        dormant_zip_button.setFixedSize(90, 30)

        dormant_zip_button.clicked.connect(self.zip_file)

        Layout = QHBoxLayout(self)
        Layout.addWidget(dormant_clearAll_button)
        Layout.addWidget(self.dormant_delete_button)
        Layout.addWidget(dormant_zip_button)
        Layout.addWidget(treeView)

        #dormant_clearAll_button.clicked.connect(self.clear_Files())

        self.UnUsed_Tab.setLayout(Layout)
示例#9
0
    def __initFilesModel(self):
        model = QFileSystemModel()
        model.setReadOnly(True)
        model.setRootPath('C:/')

        return model
示例#10
0
class AssetBrowser(QMainWindow, Ui_MainWindow, PlaygroundModule):
    Name = "asset_browser"

    def __init__(self, module_manager):
        super(AssetBrowser, self).__init__()
        self.setupUi(self)

        self.init_module(module_manager)

        self.dir_model = QFileSystemModel()
        self.dir_model.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs)
        self.dir_model.setReadOnly(False)

        self.dir_view.setModel(self.dir_model)
        self.dir_view.hideColumn(1)
        self.dir_view.hideColumn(2)
        self.dir_view.hideColumn(3)

        self.file_model = QFileSystemModel()
        self.file_model.setFilter(QDir.NoDotAndDotDot | QDir.Files)
        self.file_model.setReadOnly(False)

        self.file_view.setModel(self.file_model)

        self.dock = self.modules_manager.new_docked(self, self.Name, "Asset browser",
                                                    Qt.BottomDockWidgetArea)

        self.modules_manager.main_window.splitDockWidget(self.dock,
                                                         self.modules_manager["asset_view"].dock, Qt.Horizontal)

    def on_open_project(self, project):
        project_dir = project.project_dir
        path = os.path.join(project_dir)

        self.dir_model.setRootPath(path)
        self.file_model.setRootPath(path)

        self.dir_view.setRootIndex(self.dir_model.index(path))
        self.file_view.setRootIndex(self.file_model.index(path))

    def dir_clicked(self, idx):
        path = self.dir_model.fileInfo(idx).absoluteFilePath()

        self.file_view.setRootIndex(self.file_model.setRootPath(path))

    def file_doubleclicked(self, idx):
        fileinfo = self.file_model.fileInfo(idx)

        path = fileinfo.absoluteFilePath()
        ext = fileinfo.suffix()
        asset_name = path.replace(self.project_manager.project_dir, '').replace('/src/', '').split('.')[0]

        self.modules_manager.open_asset(path, asset_name, ext)

    def file_clicked(self, idx):
        fileinfo = self.file_model.fileInfo(idx)

        path = fileinfo.absoluteFilePath()
        ext = fileinfo.suffix()
        asset_name = path.replace(self.project_manager.project_dir, '').replace('/src/', '').split('.')[0]

        self.modules_manager.show_asset(path, asset_name, ext)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = 'ipetrash'

from PyQt5.QtWidgets import QTreeView, QFileSystemModel, QApplication
from PyQt5.QtCore import QDir

if __name__ == '__main__':
    app = QApplication([])

    model = QFileSystemModel()
    model.setRootPath(QDir.currentPath())
    model.setReadOnly(False)

    mw = QTreeView()
    mw.setModel(model)
    mw.setRootIndex(model.index(QDir.currentPath()))
    mw.show()

    app.exec()
示例#12
0
class MyMainWindow(QMainWindow):

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.config_window()
        self.create_widgets()
        self.config_widgets()
        self.create_menubar()
        self.bind_widgets()
        self.show_widgets()

    def config_window(self):
        self.setWindowTitle('DirectoPy')
        self.setMinimumHeight(600)
        self.setMinimumWidth(1000)

    def create_widgets(self):
        self.central_widget = QWidget()
        self.main_layout = QGridLayout()
        self.moveup_button = QPushButton('Collapse all', self)
        self.goto_lineedit = QLineEdit('', self)
        self.goto_button = QPushButton('Go', self)
        self.folder_view = QTreeView(self)
        self.file_view = QTreeView(self)
        self.folder_model = QFileSystemModel(self)
        self.file_model = QFileSystemModel(self)

    def config_widgets(self):
        self.main_layout.addWidget(self.moveup_button, 0, 0)
        self.main_layout.addWidget(self.goto_lineedit, 0, 1, 1, 2)
        self.main_layout.addWidget(self.goto_button, 0, 3)
        self.main_layout.addWidget(self.folder_view, 1, 0, 1, 2)
        self.main_layout.addWidget(self.file_view, 1, 2, 1, 2)

        self.central_widget.setLayout(self.main_layout)

        # Кнопка "вверх"
        self.moveup_button.setMaximumWidth(100)

        # Кнопка "перейти"
        self.goto_button.setMaximumWidth(70)
        self.setCentralWidget(self.central_widget)
        # панели
        self.folder_model.setRootPath(None)
        self.folder_model.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        self.folder_view.setModel(self.folder_model)
        self.folder_view.setRootIndex(self.folder_model.index(None))
        self.folder_view.clicked[QModelIndex].connect(self.clicked_onfolder)
        self.folder_view.hideColumn(1)
        self.folder_view.hideColumn(2)
        self.folder_view.hideColumn(3)

        self.file_model.setFilter(QDir.Files)
        self.file_view.setModel(self.file_model)
        self.file_model.setReadOnly(False)
        self.file_view.setColumnWidth(0, 200)
        self.file_view.setSelectionMode(QAbstractItemView.ExtendedSelection)

    # открытие папки при нажати на неё в окне папок
    def clicked_onfolder(self, index):
        selection_model = self.folder_view.selectionModel()
        index = selection_model.currentIndex()
        dir_path = self.folder_model.filePath(index)
        self.file_model.setRootPath(dir_path)
        self.file_view.setRootIndex(self.file_model.index(dir_path))

    # ф-я открытия нового файла
    def open_file(self):
        index = self.file_view.selectedIndexes()
        if not index:
            return
        else:
            index = index[0]
        file_path = self.file_model.filePath(index).replace('/', '\\')
        print(file_path)
        self.file_view.update()

    # ф-я создания нового файла
    def new_file(self):
        global file_name
        index = self.folder_view.selectedIndexes()
        if len(index) > 0:
            path = self.folder_model.filePath(index[0])
            for i in range(1, 9999999999999999):
                if not os.path.isfile(os.path.join(path, "newfile{}.txt".format(i))):
                    file_name = os.path.join(path, "newfile{}.txt".format(i))
                    break
            file_name = os.path.abspath(file_name)
            open(file_name, 'w').close()
        else:
            print("Please, select folder")

    # ф-я удаления файла
    def delete_file(self):
        indexes = self.file_view.selectedIndexes()
        for i in indexes:
            self.file_model.remove(i)

    # ф-я переименования файла
    def rename_file(self):
        index = self.file_view.selectedIndexes()
        if not index:
            return
        else:
            index = index[0]
        self.file_view.edit(index)

    # ф-я копирования файла
    def copy_file(self):
        print("COPY")
        ask = QFileDialog.getExistingDirectory(self, "Open Directory", "C:\\",
                                               QFileDialog.ShowDirsOnly |
                                               QFileDialog.DontResolveSymlinks)
        new_path = ask.replace('\\', '/')
        indexes = self.file_view.selectedIndexes()[::4]
        for i in indexes:
            new_filename = new_path + '/' + self.file_model.fileName(i)
            copy2(self.file_model.filePath(i), new_filename)

    # ф-я возвращения к корню пути
    def colapse(self):
        self.folder_view.collapseAll()

    # ф-я перемещения в заданную директорию
    def go_to(self):
        dir_path = self.goto_lineedit.text().replace('\\', '/')
        print(dir_path)
        self.file_model.setRootPath(dir_path)
        self.file_view.setRootIndex(self.file_model.index(dir_path))

        #self.file_model.setRootPath()

    # ф-я перемещения файла
    def move_file(self):
        print("MOVE")
        ask = QFileDialog.getExistingDirectory(self, "Open Directory", "C:\\",
                                               QFileDialog.ShowDirsOnly |
                                               QFileDialog.DontResolveSymlinks)
        if ask == '':
            return
        new_path = ask.replace('\\', '/')
        indexes = self.file_view.selectedIndexes()[::4]
        for i in indexes:
            new_filename = new_path + '/' + self.file_model.fileName(i)
            move(self.file_model.filePath(i), new_filename)

    # ф-я создания новой папки
    def new_folder(self):
        global file_name
        index = self.folder_view.selectedIndexes()
        if len(index) > 0:
            path = self.folder_model.filePath(index[0])
            for i in range(1, 9999999999999999):
                if not os.path.isdir(os.path.join(path, "newfolder{}".format(i))):
                    file_name = os.path.join(path, "newfolder{}".format(i))
                    break
            file_name = os.path.abspath(file_name)
            os.mkdir(file_name)
        else:
            print("Please, select folder")

    # ф-я удаления папки
    def delete_folder(self):
        indexes = self.folder_view.selectedIndexes()
        for i in indexes:
            self.folder_model.remove(i)

    # ф-я переименования папки
    def rename_folder(self):
        index = self.folder_view.selectedIndexes()
        if not index:
            return
        else:
            index = index[0]
        self.folder_view.edit(index)

    # ф-я закрытия окна файлового менеджера
    def exit_application(self):
       print("EXIT")
       self.close()

    # задавание функции каждой кнопке
    def bind_widgets(self):
        self.open_file_action.triggered.connect(self.open_file)
        self.new_file_action.triggered.connect(self.new_file)
        self.delete_file_action.triggered.connect(self.delete_file)
        self.rename_file_action.triggered.connect(self.rename_file)
        self.copy_file_action.triggered.connect(self.copy_file)
        self.move_file_action.triggered.connect(self.move_file)
        self.exit_action.triggered.connect(self.exit_application)
        self.new_folder_action.triggered.connect(self.new_folder)
        self.delete_folder_action.triggered.connect(self.delete_folder)
        self.rename_folder_action.triggered.connect(self.rename_folder)


        self.goto_button.clicked.connect(partial(self.go_to))
        self.moveup_button.clicked.connect(partial(self.colapse))

    # создание меню
    def create_menubar(self):

        self.exit_action = QAction('Exit', self)
        self.exit_action.setShortcut('Ctrl+Q')

        self.new_file_action = QAction('New file', self)
        self.new_file_action.setShortcut('F4')

        self.open_file_action = QAction('Open file', self)
        self.open_file_action.setShortcut('F3')

        self.rename_file_action = QAction('Rename file', self)
        self.rename_file_action.setShortcut('F2')

        self.delete_file_action = QAction('Remove file', self)
        self.delete_file_action.setShortcut(QKeySequence.Delete)

        self.copy_file_action = QAction('Copy folder...', self)
        self.copy_file_action.setShortcut(QKeySequence.Copy)

        self.move_file_action = QAction('Move folder...', self)
        self.move_file_action.setShortcut(QKeySequence.Cut)

        self.new_folder_action = QAction('New folder', self)
        self.new_folder_action.setShortcut('Ctrl+Shift+N')

        self.delete_folder_action = QAction('Delete folder', self)
        self.delete_folder_action.setShortcut('Ctrl+Shift+Del')

        self.rename_folder_action = QAction('Rename folder', self)
        self.rename_folder_action.setShortcut('Ctrl+Shift+R')

        self.menubar = self.menuBar()
        self.file_menu = self.menubar.addMenu('File')
        self.file_menu.addAction(self.new_file_action)
        self.file_menu.addAction(self.open_file_action)
        self.file_menu.addAction(self.rename_file_action)
        self.file_menu.addAction(self.delete_file_action)
        self.file_menu.addAction(self.copy_file_action)
        self.file_menu.addAction(self.move_file_action)
        self.file_menu.addSeparator()
        self.file_menu.addAction(self.exit_action)

        self.folder_menu = self.menubar.addMenu('Folder')
        self.folder_menu.addAction(self.new_folder_action)
        self.folder_menu.addAction(self.delete_folder_action)
        self.folder_menu.addAction(self.rename_folder_action)

    def show_widgets(self):
        self.setLayout(self.main_layout)
class MainWindow(QtWidgets.QMainWindow):
    connection_status = 0
    file_path = ''
    ftp = ftplib.FTP('')

    def __init__(self):
        super(MainWindow, self).__init__()
        self.ui = uic.loadUi('ftp.ui', self)
        self.model = QFileSystemModel()
        self.setFixedSize(810, 563)
        self.init_ui()
        self.bind_event()
        self.set_validation_type()

    def init_ui(self):
        self.populate_local_tree_view()
        self.show()

    def populate_local_tree_view(self):
        self.fsm = QFileSystemModel(self)
        self.fsm.setRootPath('')
        self.fsm.setReadOnly(True)
        # self.fsm.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
        self.ui.local_tree_view.setModel(self.fsm)
        self.local_tree_view.setRootIndex(self.fsm.index(self.fsm.rootPath()))
        self.ui.local_tree_view.setAnimated(False)
        self.ui.local_tree_view.setIndentation(20)
        self.ui.local_tree_view.setSortingEnabled(True)

    def bind_event(self):
        self.ui.btn_login.clicked.connect(self.on_login_click)
        self.ui.local_tree_view.clicked.connect(self.on_tree_view_clicked)
        # self.ui.tableView.doubleClicked.connect(self.on_click)

    def on_tree_view_clicked(self, index):
        index_item = self.fsm.index(index.row(), 0, index.parent())
        path = str(self.fsm.filePath(index_item))
        self.selected_file_path = path

    def set_validation_type(self):
        only_int = QIntValidator()
        self.ui.input_port_number.setValidator(
            only_int)  # allowing only integer input
        self.ui.input_password.setEchoMode(QLineEdit.Password)

    @pyqtSlot()
    def on_login_click(self):
        if self.connection_status == 0:
            host_name = self.ui.input_host_name.text().strip()
            usr = self.ui.input_username.text().strip()
            password = self.ui.input_password.text().strip()
            port_number = self.ui.input_port_number.text().strip()

            if is_not_blank(host_name) and is_not_blank(usr) and is_not_blank(
                    password) and is_not_blank(port_number):
                port_number = int(port_number)
                try:
                    self.ftp.connect(host_name, port_number)
                    self.ftp.login(usr, password)

                    self.add_item_to_log_list_widget("login successful")
                    self.ui.btn_login.setText("Disconnect")
                    self.connection_status = 1
                    self.get_remote_file()
                except ftplib.all_errors:
                    self.add_item_to_log_list_widget(
                        "logged in incorrect credentials")
                    show_error_dialog("Please check your credentials")
            else:
                show_error_dialog("Please enter all credentials")
        else:
            self.logout()

    def get_remote_file(self):
        self.model = QStandardItemModel()
        self.model.setColumnCount(3)
        self.model.setHorizontalHeaderLabels(['Name', 'Size', 'Last Modified'])

        files = self.ftp.nlst()
        i = 0
        for filename in files:
            self.add_row_item(i, 0, self.model, filename)
            try:
                self.ftp.voidcmd('TYPE I')
                size = str(self.ftp.size(filename))
                size = size + " KB"
                self.add_row_item(i, 1, self.model, size)
                modified_time = self.ftp.sendcmd('MDTM ' + filename)
                formatted_time = datetime.strptime(
                    modified_time[4:],
                    "%Y%m%d%H%M%S").strftime("%d %B %Y %H:%M:%S")
                self.add_row_item(i, 2, self.model, formatted_time)
                self.add_item_to_log_list_widget(
                    "remote directory listing successful")
            except:
                item = QStandardItem(filename)
                item.setTextAlignment(Qt.AlignVCenter)
                item.setEditable(False)
                self.model.setItem(i, 0, item)
                item.setIcon(QIcon("static/ic_folder.png"))
            i += 1
        self.ui.tableView.setModel(self.model)
        self.ui.tableView.setSelectionBehavior(QTableView.SelectRows)
        self.set_property()

    @staticmethod
    def add_row_item(row, column, model, text):
        item = QStandardItem(text)
        item.setTextAlignment(Qt.AlignVCenter)
        item.setEditable(False)
        model.setItem(row, column, item)

    def set_property(self):
        self.ui.tableView.setColumnWidth(0, 120)
        self.ui.tableView.setColumnWidth(1, 120)
        self.ui.tableView.setColumnWidth(2, 160)
        self.ui.tableView.setShowGrid(False)
        header = self.ui.tableView.horizontalHeader()
        header.setDefaultAlignment(Qt.AlignVCenter)

    def contextMenuEvent(self, event):
        self.menu = QMenu(self)
        rename_action = QAction('Rename', self)
        rename_action.triggered.connect(lambda: self.rename_slot(event))
        self.menu.addAction(rename_action)

        delete_action = QAction('Delete', self)
        delete_action.triggered.connect(lambda: self.delete_slot(event))
        self.menu.addAction(delete_action)

        download_action = QAction('Download', self)
        download_action.triggered.connect(lambda: self.download_slot(event))
        self.menu.addAction(download_action)

        create_dir_action = QAction('New Dir', self)
        create_dir_action.triggered.connect(
            lambda: self.create_dir_slot(event))
        self.menu.addAction(create_dir_action)

        upload_file_action = QAction('Upload', self)
        upload_file_action.triggered.connect(
            lambda: self.upload_file_slot(event))
        self.menu.addAction(upload_file_action)

        self.menu.popup(QCursor.pos())

    @pyqtSlot()
    def rename_slot(self, event):
        # indexes = self.ui.tableView.selectionModel().selectedRows()
        # for index in sorted(indexes):
        # print('Row %d is selected' % index.row())
        for index in sorted(self.ui.tableView.selectionModel().selectedRows()):
            selected_filename = self.model.data(
                self.model.index(index.row(), 0))
            new_name = show_input_dialog(self, "Rename", "New Name")
            if new_name != '' and len(new_name) != 0:
                try:
                    self.ftp.rename(selected_filename, new_name)
                    self.get_remote_file()
                    self.add_item_to_log_list_widget(selected_filename +
                                                     " change with " +
                                                     new_name +
                                                     " successfully on remote")
                except:
                    show_error_dialog("Unexpected error occurred")
            else:
                show_error_dialog("Invalid file name")
            break  # just rename one file

    @pyqtSlot()
    def delete_slot(self, event):
        for index in sorted(self.ui.tableView.selectionModel().selectedRows()):
            try:
                selected_filename = self.model.data(
                    self.model.index(index.row(), 0))
                self.ftp.rmd(selected_filename)
                self.add_item_to_log_list_widget(selected_filename +
                                                 " deleted on remote")
            except:
                print("")

    @pyqtSlot()
    def download_slot(self, event):
        for index in sorted(self.ui.tableView.selectionModel().selectedRows()):
            selected_filename = str(
                self.model.data(self.model.index(index.row(), 0)))
            try:
                local_file = open(selected_filename, 'wb')
                self.ftp.retrbinary('RETR ' + selected_filename,
                                    local_file.write, 1024)
                local_file.close()
                self.add_item_to_log_list_widget(
                    selected_filename + "file is downloaded successfully")
            except Exception as e:
                print(e)  # show_error_dialog("Unexpected error occurred")

    @pyqtSlot()
    def create_dir_slot(self, event):
        self.add_item_to_log_list_widget(
            "test file is downloaded successfully")
        file_name = show_input_dialog(self, "New Directory", "Directory Name")
        try:
            if file_name != '' and len(file_name) != 0:
                self.ftp.mkd(file_name)
                self.get_remote_file()
                self.add_item_to_log_list_widget(file_name +
                                                 " created successfully")
            else:
                show_error_dialog("Invalid directory name")
        except:
            print("")

    @pyqtSlot()
    def upload_file_slot(self, event):
        try:
            if os.path.isfile(self.file_path):
                file_name = os.path.basename(self.file_path)
                self.ftp.storbinary('STOR ' + file_name,
                                    open(self.file_path, 'rb'))
                self.get_remote_file()
                self.add_item_to_log_list_widget(file_name +
                                                 " uploaded successfully")
        except:
            show_error_dialog("Please choose only one file")

    @pyqtSlot()
    def on_delete_file_click(self):
        files = list(self.ftp.nlst())
        for f in files:
            self.ftp.delete(f)

    def get_size(self, directory):
        size = 0
        for file in self.ftp.nlst(directory):
            size += self.ftp.size(file)
        return size

    def add_item_to_log_list_widget(self, log):
        self.ui.log_list_widget.addItem("status\t" + log)

    def logout(self):
        self.ftp.close()
        self.add_item_to_log_list_widget("logout successfully")
        self.connection_status = 0
        self.ui.btn_login.setText("Connect")
示例#14
0
class MainWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.left = 10
        self.top = 10
        self.width = 400
        self.height = 500
        self.leftPanelWidth = 250
        self.processed_image: Segmented_image = None
        self.initUI()

    def initUI(self):
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.model = QFileSystemModel()
        self.model.setRootPath(
            r'C:\Users\kkozi\Documents\WORKSPACE\pomwj_projekt\data ')
        self.model.setReadOnly(True)
        tmpIdx = self.model.index(
            r'C:\Users\kkozi\Documents\WORKSPACE\pomwj_projekt\data')

        self.tree = QTreeView()
        self.tree.setModel(self.model)
        self.tree.doubleClicked.connect(self.SetProcessedImage)
        self.tree.setRootIndex(tmpIdx)

        self.img = QPixmap(
            r'C:\Users\kkozi\Documents\WORKSPACE\pomwj_projekt\data\no_image.jpg'
        )
        self.imgLabel = QLabel()
        self.imgLabel.setAlignment(Qt.AlignCenter)
        self.imgLabel.setContentsMargins(30, 0, 0, 30)
        self.imgLabel.setStyleSheet("text-align: right; color: white;")
        self.imgLabel.setPixmap(self.img)

        splitter = QSplitter(Qt.Horizontal)
        splitter.addWidget(self.tree)
        splitter.addWidget(self.imgLabel)

        self.processing_wdg = Processing_data_widget()
        self.processing_wdg.process_btn.clicked.connect(self.MakeSegmentation)

        downLayout = QHBoxLayout()
        downLayout.addWidget(splitter)
        downLayout.addWidget(self.processing_wdg)

        mainLayout = QVBoxLayout(self)
        mainLayout.addLayout(downLayout)

    def SetProcessedImage(self, index):
        try:
            path = self.model.filePath(index)
            self.processed_image = Segmented_image()
            self.processed_image.SetImage(path)
            self.processing_wdg.SetFileParams(
                path, self.processed_image.GetColorType())
            if self.ImgIsRGB():
                self.processing_wdg.SetConvertBtnActive()
                self.processing_wdg.convert_btn.clicked.connect(
                    self.ConvertToHSV)
            else:
                self.processing_wdg.SetConvertBtnDisactive()
            self.processing_wdg.process_btn.setDisabled(False)
            self.ShowSelectedImage()

            if not self.processed_image.IsSetImage():
                QMessageBox.information(self, "Segmented_image Viewer",
                                        "Cannot load %s." % 'image')

        except FileFormatError as ex:
            QMessageBox.information(self, 'Format no supported',
                                    '{0}'.format(str(ex.message)),
                                    QMessageBox.Ok)

    def ShowSelectedImage(self):
        self.img = QPixmap.fromImage(self.processed_image.GetQImageFromImage())
        self.img = self.img.scaled(self.imgLabel.width() * 0.9,
                                   self.imgLabel.height() * 0.9,
                                   Qt.KeepAspectRatio)
        self.imgLabel.setPixmap(self.img)
        self.imgLabel.resize(self.width * 0.95, self.height * 0.95)

    def MakeSegmentation(self):
        progress_dialog = QProgressDialog()
        segmentation = Segmentation(self.processed_image)
        progress_dialog.setValue(10)
        seg_img = segmentation.makeSegment(self.processing_wdg.GetMinObjSize(),
                                           self.processing_wdg.GetThrDown(),
                                           self.processing_wdg.GetThrUp())
        progress_dialog.setValue(30)
        self.processed_image = Segmented_image.FromSITKImage(seg_img)
        progress_dialog.setValue(50)
        self.processing_wdg.SetCellsNumResult(segmentation.GetCellsNum())
        progress_dialog.setValue(80)
        self.ShowSelectedImage()
        progress_dialog.setValue(100)
        progress_dialog.close()

    def resizeEvent(self, event):
        self.img = self.img.scaled(self.imgLabel.width() * 0.9,
                                   self.imgLabel.height() * 0.9,
                                   Qt.KeepAspectRatio)
        self.imgLabel.setPixmap(self.img)
        self.imgLabel.resize(self.width * 0.95, self.height * 0.95)

    def ImgIsRGB(self):
        if self.processed_image.colorType == 'RGB':
            return True
        else:
            return False

    def ConvertToHSV(self):
        progress_dialog = QProgressDialog()
        self.processing_wdg.SetConvertBtnDisactive()
        image = self.processed_image.ConvertToHSV()
        self.processed_image = Segmented_image.FromSITKImage(image)
        self.ShowSelectedImage()
        progress_dialog.close()
示例#15
0
class EditorTextosDlg(QWidget):
    def __init__(self):
        super().__init__()
        self.fileName = ["Editor de texto", ".txt"]
        self.initUI()

    def initUI(self):

        # Sección de seleccionar carpeta
        folderSectionTitle = QLabel("Carpeta")
        self.fileFolder = QLineEdit()  # Línea donde está la carpeta
        self.fileFolder.setReadOnly(
            True
        )  # Hacemos que solo muestre el path y no podamos escribir en ella
        self.selectButton = QPushButton("Seleccionar")  # Botón de la sección

        # Sección de listado de directorios y archivos
        filesSectionTitle = QLabel("Archivos")  # Título de la sección
        self.fileTree = QTreeView()  # Crea una vista en forma de árbol
        self.fileSystemModel = QFileSystemModel(
            self.fileTree)  # Construye un modelo de los archivos del sistema
        self.fileSystemModel.setReadOnly(
            True)  # Hacemos que solo sea de modo lectura
        modelRoot = self.fileSystemModel.setRootPath(
            "/home"
        )  # /home será el directorio que se mostrará por defecto cuando iniciemos la app
        self.fileTree.setModel(
            self.fileSystemModel
        )  # Seteamos el modelo que creamos como modelo de nuestra vista en forma de árbol
        self.fileTree.setRootIndex(
            modelRoot
        )  # Seteamos el directorio por defecto que establecimos anteriormente (/home)
        self.fileTree.hideColumn(1)  # Escondemos el tamaño
        self.fileTree.hideColumn(2)  # Escondemos el tipo de archivo
        self.fileTree.hideColumn(
            3)  # Escondemos la fecha de modificación del archivo
        self.fileTree.setHeaderHidden(
            True)  # Escondemos la cabecera de la sección

        # Sección de texto
        self.textEdit = QTextEdit(
        )  # Cuadro de texto donde podremos escribir para modificar y guardar archivos

        # Sección de botones
        self.saveButton = QPushButton("Guardar")  # Botón de guardar
        self.saveAsButton = QPushButton(
            "Guardar como")  # Botón de guardar como

        # Creamos un diseño horizontal donde añadiremos los componentes de la sección de carpeta
        hbox = QHBoxLayout()
        hbox.addWidget(folderSectionTitle)
        hbox.addWidget(self.fileFolder)
        hbox.addWidget(self.selectButton)

        # Creamos un diseño vertical donde añadimos el horizontal que hemos creado previamente
        vbox = QVBoxLayout()
        vbox.setSpacing(30)
        vbox.addLayout(hbox)

        # Creamos una cuadrícula donde añadiremos los componentes de la sección de archivo especificando sus coordenadas
        grid = QGridLayout()
        grid.setSpacing(10)
        grid.addWidget(filesSectionTitle, 0, 0)
        grid.addWidget(self.fileTree, 1, 0, 1, 3)
        grid.addWidget(self.textEdit, 1, 3, 1, 5)
        # Añadimos el diseño de cuadricula de archivos al diseño vertical
        vbox.addLayout(grid)

        # Creamos un diseño horizontal donde añadiremos los componentes de la sección de botones
        # Añadimos margen después de los botones para que estén pegados a la esquina inferior izquierda
        self.buttomsLayout = QHBoxLayout()
        self.buttomsLayout.addWidget(self.saveButton)
        self.buttomsLayout.addWidget(self.saveAsButton)
        self.buttomsLayout.addStretch()
        # Añadimos el diseño de botones al diseño vertical
        vbox.addLayout(self.buttomsLayout)

        self.setLayout(
            vbox)  # Establecemos el diseño vertical como diseño principal
        self.setWindowTitle("Editor de texto")  # Título de la ventana
        self.setGeometry(
            300, 150, 1000,
            700)  # Establecemos el tamaño y posicionamiento de la ventana
        self.show()  # Mostramos la ventana

        # Conectamos los botones a diferentes métodos
        self.selectButton.clicked.connect(
            self.openFolders)  # Dispara el método de abrir carpeta
        self.fileTree.doubleClicked.connect(
            self.doubleClickedTreeView
        )  # Dispara el método de desplegar carpeta en la sección de archivos
        self.saveButton.clicked.connect(
            self.saveFiles)  # Dispara el método de guardar archivo
        self.saveAsButton.clicked.connect(
            self.saveAsFiles)  # Dispara el método de guardar como

    def openFolders(self):  # Método de abrir carpeta
        directory = controller.openFolder(
            self
        )  # Dispara el método de seleccionar carpeta, el cual abre una ventana emergente
        modelRoot = self.fileSystemModel.setRootPath(
            directory)  # Establece la raiz el árbol en la carpeta seleccionada
        self.fileTree.setRootIndex(
            modelRoot)  # Muestra esta carpeta en la sección de archivos
        self.fileFolder.setText(
            directory
        )  # Muestra el path de la carpeta en la sección de carpeta

    def doubleClickedTreeView(self, index):  # Método de desplegar carpeta
        filedata = controller.doubleClickedTreeView(
            self, index
        )  # Dispara el método de doble click en la sección de archivos
        self.textEdit.setText(
            filedata)  # Muestra el contenido en el cuadro de texto

    def saveFiles(self):  # Método de guardar archivo
        controller.saveFile(self)  # Dispara el método de guardar archivo

    def saveAsFiles(self):  # Método de guardar como
        controller.saveAsFile(self)  # Dispara el método de guardar como

    def closeEvent(
            self,
            event):  # Método que se despliega cuando se intenta cerrar la app
        reply = QMessageBox.question(self, "Confirmación",
                                     "¿Deseas cerrar la app?",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()  # Cerramos la app
        else:
            event.ignore()  # No cerramos la app (ignoramos la señal de cerrar)
示例#16
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        dockWidget = QDockWidget("Explorer", self)

        self.editor = QPlainTextEdit()
        self.editor.document().setDefaultFont(QFont("monospace"))
        self.editor.zoomIn(2)

        self.explorer = QTreeView()
        self.model = QFileSystemModel(self.explorer)
        self.root = self.model.setRootPath("../..")
        self.explorer.setModel(self.model)
        self.explorer.setRootIndex(self.root)
        self.file_path = None

        # Instances of menus and message
        self.custom_menu = Custom_menu(self, self.explorer, self.model,
                                       self.editor, app)
        self.menu = Menu(self, self.explorer, self.editor, self.model)
        self.message = Message(self)

        # Menu bar
        self.file_menu = self.menuBar().addMenu("&File")
        self.help_menu = self.menuBar().addMenu("&Help")
        self.menu.menu_actions()

        # Other custom tweaks
        self.explorer.setSortingEnabled(True)
        self.explorer.setMinimumWidth(400)
        self.explorer.setContextMenuPolicy(Qt.CustomContextMenu)
        self.resize(1500, 900)

        # Enabling renaming on context menu
        self.model.setReadOnly(False)
        self.explorer.setEditTriggers(self.explorer.NoEditTriggers)

        # Change default explorers column width
        self.header = self.explorer.header()
        self.header.setSectionResizeMode(0, QHeaderView.Interactive)
        self.header.setDefaultSectionSize(200)
        self.header.setSectionResizeMode(1, QHeaderView.ResizeToContents)
        self.header.setSectionResizeMode(2, QHeaderView.ResizeToContents)

        # Setting editor as central widget
        self.setCentralWidget(self.editor)
        self.addDockWidget(Qt.LeftDockWidgetArea, dockWidget)

        # Setting view as widget of dock widget
        dockWidget.setWidget(self.explorer)
        dockWidget.setFloating(False)

        ### Double & right click
        self.explorer.doubleClicked.connect(self.custom_menu.on_double_click)
        self.explorer.customContextMenuRequested.connect(
            self.custom_menu.context_menu)

    def closeEvent(self, e):
        """This function prevents from closing without saving,
		 it works with the "Close" event"""

        if not self.editor.document().isModified():
            return
        answer = self.message.ask_for_confirmation()
        if answer == QMessageBox.Save:
            if not self.menu.save():
                e.ignore()
        elif answer == QMessageBox.Cancel:
            e.ignore()
示例#17
0
class Window(QMainWindow):
    save_crop_signal = pyqtSignal()

    samling_ratio = 60

    class State(Enum):
        Initial = 1
        OneCursorPlaced = 2
        TwoCursorPlaced = 3

    def __init__(self):
        super().__init__()
        self.player = QMediaPlayer()
        self.ui = Ui_MainWindow()
        # setup main Window's UI
        self.ui.setupUi(self)
        self._setup_connections()
        self._setup_matplotlib()
        self._setup_directory_browser()
        self.play_timer = QTimer(self)
        self.play_timer.timeout.connect(self.plot_animator)
        self.ymax = 30000
        self.state = None
        self.crop_line_1_pos = None
        self.crop_line_2_pos = None
        self.play_limit = (0, 0)
        self.current_zoom = 100
        self.seconds_to_prefetch = 60
        self.minimum_file_file_length = 2.5
        self.save_crop_signal.connect(self.save_crop_to_file)

    def _setup_matplotlib(self):

        self.figure = Figure()
        self.canvas = FigureCanvas(self.figure)
        layout = self.ui.graph_widget.layout()
        layout.addWidget(self.canvas)
        self.canvas_click_connection = None
        self.canvas_scroll_connection = None
        self.subplot = self.figure.add_subplot(111)

        self.audio_plot, = self.subplot.plot([0], [0],
                                             '-',
                                             color=(0.70, 0.70, 0.70))
        self.playIndicator, = self.subplot.plot([0], [0], '^')
        self.crop_line_1, = self.subplot.plot([], [], '-r')
        self.crop_line_2, = self.subplot.plot([], [], '-r')
        self.ui.vertical_splitter.setSizes([2, 12])

    def _setup_directory_browser(self):
        curdir = os.path.abspath(os.path.curdir)
        self.file_system_model = QFileSystemModel(self)
        self.file_system_model.setReadOnly(True)
        self.file_system_model.setFilter(QDir.AllDirs | QDir.AllEntries
                                         | QDir.NoDotAndDotDot)
        self.file_system_model.setNameFilters(['*.wav', '*.txt'])
        self.file_system_model.setNameFilterDisables(False)

        self.ui.directory_view.setModel(self.file_system_model)
        self.file_system_model.setRootPath(curdir)
        index = self.file_system_model.index(curdir)
        self.ui.directory_view.setRootIndex(index)
        self.ui.directory_view.hideColumn(1)
        self.ui.directory_view.hideColumn(2)
        self.ui.directory_view.hideColumn(3)
        # index: QModelIndex = model.index(os.path.abspath(os.path.curdir))
        # self.ui.directory_view.expand(index);
        # self.ui.directory_view.scrollTo(index)
        # self.ui.directory_view.setCurrentIndex(index)
        self.ui.directory_view.doubleClicked.connect(self.file_selected)

    def plot(self, ydata_byte, start_pos=0):
        ''' plot some random stuff '''
        ploty = numpy.fromstring(ydata_byte, numpy.int16)
        plotdatay = ploty[0:len(ploty):Window.samling_ratio]
        plotdatax = [
            x for x in range(start_pos,
                             len(ploty) + start_pos, Window.samling_ratio)
        ]

        self.set_view_range(start_pos, plotdatax[-1])
        self.view_limit_range = (start_pos, plotdatax[-1])
        _max = max(plotdatay)
        self.figure.get_axes()[0].set_ylim(-_max, _max)
        print("The real plot limit", (start_pos, plotdatax[-1]))
        self.audio_plot.set_data(plotdatax, plotdatay)
        # refresh canvas
        self.canvas.draw()

    def set_view_range(self, start, end):
        self.figure.get_axes()[0].set_xlim(start, end)
        self.current_view = [start, end]

    def plot_animator(self):

        # current_music_time = self.play_started_audio_time + diff
        current_time_ms = self.player.position()
        current_music_frame = int(
            (current_time_ms * self.wave.getframerate()) / 1000)

        self.playIndicator.set_data([current_music_frame], [0])
        self.canvas.draw()
        if current_time_ms >= self.play_limit[1]:
            self.player.pause()
            self.play_timer.stop()
            self.playIndicator.set_data(self.crop_line_2_pos, 0)
        self.canvas.draw()

    def _setup_connections(self):
        self.player.stateChanged.connect(self.player_status_changed)
        self.player.positionChanged.connect(self.playback_progress_change)

    def toggle_pause(self):
        if self.playing:
            self.player.pause()
            self.play_timer.stop()
        else:
            self.player.play()

            self.play_timer.start()
        self.playing = not self.playing

    def seek(self, pos):
        self.player.setPosition(pos)
        self.player.play()
        if self.player.state() != QMediaPlayer.PlayingState:
            self.player.play()
        if not self.play_timer.isActive():
            self.play_timer.start()

    def seek_frame(self, frame_pos):
        self.seek(int((frame_pos * 1000) / (self.wave.getframerate())))
        # self.seek(int(frame_pos / (self.wave.getframerate() * 1000)))

    def canvas_click_listener(self, event):
        if not event.xdata:
            return
        currentframe = event.xdata
        current_time_in_milli = int(currentframe / self.wave.getframerate() *
                                    1000)
        if (current_time_in_milli < 0):
            current_time_in_milli = 0
        current_x = int(event.xdata)
        if (current_x < 0):
            current_x = 0

        if self.state == Window.State.Initial:
            self.crop_line_1.set_data([current_x, current_x],
                                      [-self.ymax, self.ymax])
            self.crop_line_1_pos = current_x
        elif self.state == Window.State.OneCursorPlaced:
            if current_x > self.crop_line_1_pos:
                self.crop_line_2_pos = current_x
                self.crop_line_2.set_data([current_x, current_x],
                                          [-self.ymax, self.ymax])
        self.canvas.draw()
        self.seek(current_time_in_milli)

    def canvas_scroll_listener(self, event):
        current_range = self.current_view[1] - self.current_view[0]
        if current_range < 0:
            return
        if event.button == 'down':
            new_range = current_range / 1.3
        else:
            new_range = current_range * 1.3

        new_view = [event.xdata - new_range / 2, event.xdata + new_range / 2]
        count = 0
        if new_view[0] < self.view_limit_range[0]:
            new_view[1] += self.view_limit_range[0] - new_view[0]
            new_view[0] = self.view_limit_range[0]
            if new_view[1] > self.view_limit_range[1]:
                new_view[1] = self.view_limit_range[1]

        elif new_view[1] > self.view_limit_range[1]:
            new_view[0] -= new_view[1] - self.view_limit_range[1]
            new_view[1] = self.view_limit_range[1]
            if new_view[0] < self.view_limit_range[0]:
                new_view[0] = self.view_limit_range[0]
        if new_view[0] > new_view[1]:
            return
        self.figure.get_axes()[0].set_xlim(new_view[0], new_view[1])
        self.current_view = new_view
        self.canvas.draw()

    def eventFilter(self, event):
        print("New Event", event.type())
        return False

    def keyPressEvent(self, event):

        key = event.key()
        if key == Qt.Key_Space:
            self.toggle_pause()
        if key == Qt.Key_Return:

            if self.state == Window.State.Initial:
                if self.crop_line_1_pos:
                    self.state = Window.State.OneCursorPlaced
                    self.crop_line_1.set_data(
                        [self.crop_line_1_pos, self.crop_line_1_pos],
                        [-self.ymax, self.ymax])
                    self.crop_line_1.set_color("green")
                    self.canvas.draw()

            elif self.state == Window.State.OneCursorPlaced:
                if self.crop_line_2_pos:
                    self.crop_line_2.set_color("green")
                    self.zoom_to_crop()
                    self.state = Window.State.TwoCursorPlaced
                    self.ui.statusbar.showMessage(
                        "Press Enter to save the clip to file", 3000)

            elif self.state == Window.State.TwoCursorPlaced:
                self.crop_to_save = self.data[self.crop_line_1_pos *
                                              2:self.crop_line_2_pos * 2]
                self.crop_nchannel = self.wave.getnchannels()
                self.crop_stampwidth = self.wave.getsampwidth()
                self.crop_framerate = self.wave.getframerate()
                self.save_crop_signal.emit()
                self.update_cropped_plot()

        if key == Qt.Key_Backspace:
            if self.state == Window.State.OneCursorPlaced:
                self.state = Window.State.Initial
                self.crop_line_1_pos = None
                self.crop_line_1.set_color("red")
                self.crop_line_2.set_data([], [])
                self.canvas.draw()
            elif self.state == Window.State.TwoCursorPlaced:

                self.play_limit = self.play_limit_bak
                self.state = Window.State.OneCursorPlaced
                self.crop_line_2_pos = None
                self.crop_line_2.set_color("red")
                self.canvas.draw()

    @pyqtSlot(QMediaPlayer.State)
    def player_status_changed(self, x):
        if x == QMediaPlayer.StoppedState:
            self.play_timer.stop()
            pass
        elif x == QMediaPlayer.PlayingState:
            pass
        elif x == QMediaPlayer.PausedState:
            pass

    @pyqtSlot('qint64')
    def playback_progress_change(self, position):
        pass
        # self.ui.progressBar.setValue(int(position / self.player.duration() * 100))

    def read_file(self, filename):
        # reset the cursors to default values
        self.wave = wave.open(filename, 'rb')
        self.channels = self.wave.getnchannels()
        self.rate = self.wave.getframerate()
        nframes = self.seconds_to_prefetch * self.wave.getframerate()

        self.playing = False
        self.data = self.wave.readframes(nframes)
        self.total_frames_read = len(self.data) // 2
        if self.total_frames_read / self.wave.getframerate(
        ) < self.minimum_file_file_length:
            self.ui.statusbar.showMessage("The file is too short.")
            return

        self.player.setMedia(QMediaContent(QUrl.fromLocalFile(filename)))
        self.plot(self.data)
        nframes = min(self.wave.getnframes(), nframes)
        self.data_shift = 0
        self.play_limit = (0, (nframes * 1000) / self.wave.getframerate())
        self.crop_count = 0
        self.current_open_file_name = filename[:-4]

        self.toggle_pause()
        if not self.canvas_scroll_connection:
            self.canvas_click_connection = self.canvas.mpl_connect(
                "button_press_event", self.canvas_click_listener)
            self.canvas_scroll_connection = self.canvas.mpl_connect(
                "scroll_event", self.canvas_scroll_listener)
        self.crop_line_1_pos = None
        self.crop_line_2_pos = None
        self.state = Window.State.Initial
        self.crop_line_2.set_data([], [])
        self.crop_line_2.set_color("red")
        self.crop_line_1.set_data([], [])
        self.crop_line_1.set_color("red")

    def zoom_to_crop(self):
        ##TODO : make crop from line1 and line2 position
        self.set_view_range(self.crop_line_1_pos - 1000,
                            self.crop_line_2_pos + 1000)
        # cropped_data = self.data[self.crop_line_1_pos:self.crop_line_2_pos]
        self.play_limit_bak = self.play_limit
        self.play_limit = ((self.crop_line_1_pos * 1000) /
                           self.wave.getframerate(),
                           (1000 * self.crop_line_2_pos) /
                           self.wave.getframerate())
        self.seek_frame(self.crop_line_1_pos)
        self.canvas.draw()

    def update_cropped_plot(self):
        # frames remain in the total sound clip
        remaining_frames = (self.wave.getnframes()) - int(self.crop_line_2_pos)
        # time remain for compleliton of sound clip
        remaining_ms = (remaining_frames * 1000) / self.wave.getframerate()

        if remaining_ms < 3000:
            return self.crop_completed(remaining_ms)

        # the no of frames that have been loaded into memory
        frames_in_memory = int(self.total_frames_read - self.crop_line_2_pos)
        data_pos = int(self.crop_line_2_pos * 2 - self.data_shift)
        self.data_shift = self.crop_line_2_pos * 2
        # all the data from sound have been read into the memory
        if frames_in_memory == remaining_frames:
            self.data = self.data[data_pos:len(self.data)]

        else:
            # the no of maximum frames that will be showed in preview
            total_frames_required = self.seconds_to_prefetch * self.wave.getframerate(
            )
            # the no of frames that needs to be read from disk
            frames_to_read = total_frames_required - frames_in_memory
            # the file may not have that many frames, so it's the minimun of frames to read and frames in disk remain
            #  to read
            frames_that_will_be_read = min(
                self.wave.getnframes() - self.total_frames_read,
                frames_to_read)

            self.total_frames_read += frames_that_will_be_read
            self.data = self.data[data_pos:len(
                self.data)] + self.wave.readframes(frames_that_will_be_read)

        self.plot(self.data, self.crop_line_2_pos)
        # frames_remain_to_read = self.wave.getnframes() - self.total_frames_read
        self.state = Window.State.Initial
        self.play_limit = ((self.crop_line_2_pos * 1000) /
                           self.wave.getframerate(),
                           (self.total_frames_read * 1000) /
                           self.wave.getframerate())
        self.view_limit_range = (self.crop_line_2_pos, self.total_frames_read)
        self.seek_frame(self.crop_line_2_pos)
        self.crop_line_1.set_data([], [])
        self.crop_line_2.set_data([], [])
        self.crop_line_1.set_color("red")
        self.crop_line_2.set_color("red")
        self.crop_line_1_pos = None
        self.crop_line_2_pos = None

    @pyqtSlot(QModelIndex)
    def file_selected(self, index):
        filename = self.file_system_model.filePath(index)
        if filename.endswith('.txt'):
            self.text_file = QFile(filename)
            if not self.text_file.open(QFile.ReadOnly | QFile.Text):
                QMessageBox.warning(self, "Application", "Cannot read file",
                                    self.text_file.errorString())
                return
            in_stream = QTextStream(self.text_file)
            # self.ui.text_edit.setPlainText(in_stream.readAll())

            # font: QFont = self.ui.text_browser.font()
            # font.setPixelSize(40)
            # self.ui.text_browser.setFont(font)
            data = in_stream.readAll()
            self.ui.text_browser.setPlainText(data)
            self.ui.text_edit.setPlainText(data)
        else:
            try:
                self.read_file(filename)
            except:
                traceback.print_exc(2)
                self.ui.statusbar.showMessage("Reading the file failed", 300)

    @pyqtSlot()
    def save_crop_to_file(self):
        self.crop_count += 1
        wave_file = wave.open(
            self.current_open_file_name + "_crop_" + str(self.crop_count) +
            '.wav', 'wb')
        wave_file.setnchannels(self.crop_nchannel)
        wave_file.setsampwidth(self.crop_stampwidth)
        wave_file.setframerate(self.crop_framerate)
        wave_file.writeframes(self.crop_to_save)
        wave_file.close()

    def crop_completed(self, remaining_ms):
        self.state = Window.State.Initial
        self.crop_line_1.set_data([], [])
        self.crop_line_2.set_data([], [])
        self.crop_line_1.set_color("red")
        self.crop_line_2.set_color("red")
        self.crop_line_1_pos = None
        self.crop_line_2_pos = None
        self.audio_plot.set_data([], [])
        self.ui.statusbar.showMessage("Cropping this file has been completed")
        self.canvas.mpl_disconnect(self.canvas_click_connection)
        self.canvas.mpl_disconnect(self.canvas_scroll_connection)
        self.canvas_scroll_connection = None
        self.canvas_click_connection = None
        self.canvas.draw()
        self.player.stop()
        self.play_timer.stop()
        self.wave.close()
        self.ui.statusbar.showMessage(
            "Only %f seconds left thus this file is considered completed" %
            (remaining_ms / 1000))
示例#18
0
class EditorTextosDlg(QWidget):
    def __init__(self):
        super().__init__()
        self.fileName = ["Editor de texto", ".txt"]
        self.initUI()

    def initUI(self):

        folderSectionTitle = QLabel("Carpeta")
        self.fileFolder = QLineEdit()
        self.fileFolder.setReadOnly(True)
        self.selectButton = QPushButton("Seleccionar")

        filesSectionTitle = QLabel("Archivos")
        self.fileTree = QTreeView()
        self.fileSystemModel = QFileSystemModel(self.fileTree)
        self.fileSystemModel.setReadOnly(True)
        modelRoot = self.fileSystemModel.setRootPath("/home")
        self.fileTree.setModel(self.fileSystemModel)
        self.fileTree.setRootIndex(modelRoot)
        self.fileTree.hideColumn(1)
        self.fileTree.hideColumn(2)
        self.fileTree.hideColumn(3)
        self.fileTree.setHeaderHidden(True)

        self.textEdit = QTextEdit()

        self.saveButton = QPushButton("Guardar")
        self.saveAsButton = QPushButton("Guardar como")

        hbox = QHBoxLayout()
        hbox.addWidget(folderSectionTitle)
        hbox.addWidget(self.fileFolder)
        hbox.addWidget(self.selectButton)

        vbox = QVBoxLayout()
        vbox.setSpacing(30)
        vbox.addLayout(hbox)

        grid = QGridLayout()
        grid.setSpacing(10)
        grid.addWidget(filesSectionTitle, 0, 0)
        grid.addWidget(self.fileTree, 1, 0, 1, 3)
        grid.addWidget(self.textEdit, 1, 3, 1, 5)
        vbox.addLayout(grid)

        self.buttomsLayout = QHBoxLayout()
        self.buttomsLayout.addWidget(self.saveButton)
        self.buttomsLayout.addWidget(self.saveAsButton)
        self.buttomsLayout.addStretch()
        vbox.addLayout(self.buttomsLayout)

        self.setLayout(vbox)
        self.setWindowTitle("Editor de texto")
        self.setGeometry(300, 150, 1000, 700)
        self.show()

        self.selectButton.clicked.connect(self.openFolders)
        self.fileTree.doubleClicked.connect(self.doubleClickedTreeView)
        self.saveButton.clicked.connect(self.saveFiles)
        self.saveAsButton.clicked.connect(self.saveAsFiles)

    def openFolders(self):
        directory = controller.openFolder(self)
        modelRoot = self.fileSystemModel.setRootPath(directory)
        self.fileTree.setRootIndex(modelRoot)
        self.fileFolder.setText(directory)

    def doubleClickedTreeView(self, index):
        filedata = controller.doubleClickedTreeView(self, index)
        self.textEdit.setText(filedata)

    def saveFiles(self):
        controller.saveFile(self)

    def saveAsFiles(self):
        controller.saveAsFile(self)

    def closeEvent(self, event):
        reply = QMessageBox.question(self, "Confirmación",
                                     "¿Deseas cerrar la app?",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
示例#19
0
class Ui_MainWindow(object):
    def setupUi(self, windget):
        windget.resize(850, 700)
        self.h1_layout = QHBoxLayout()
        self.h2_layout = QHBoxLayout()
        self.h3_layout = QHBoxLayout()
        self.h4_layout = QHBoxLayout()
        self.h5_layout = QHBoxLayout()
        self.h6_layout = QHBoxLayout()
        self.h7_layout = QHBoxLayout()
        self.h8_layout = QHBoxLayout()
        self.h9_layout = QHBoxLayout()
        self.h10_layout = QHBoxLayout()
        self.h11_layout = QHBoxLayout()
        self.all_v_layout = QVBoxLayout()

        self.statusbar = QtWidgets.QStatusBar()
        self.toolbar = QToolBar()
        self.menubar = QMenuBar()
        self.menubar.setStyleSheet(
            "QMenuBar{background-color: rgb(240, 240, 240)}")
        self.menubar.setFixedSize(870, 22)
        self.menubar.setMaximumSize(9999, 9999)
        self.h4_layout.addWidget(self.menubar)
        self.h5_layout.addWidget(self.toolbar)

        self.file_Menu = self.menubar.addMenu("文件")

        self.file_compare = QAction(QIcon('exit.png'), '&对比')
        self.file_compare.setShortcut('Shift+F10')
        self.file_compare.setStatusTip('对比文件')
        self.file_Menu.addAction(self.file_compare)

        self.file_save = QAction(QIcon('exit.png'), '&保存')
        self.file_save.setShortcut('Ctrl+s')
        self.file_save.setStatusTip('保存备案比对结果')
        self.file_Menu.addAction(self.file_save)

        self.file_open = QAction(QIcon('exit.png'), '&打开')
        self.file_open.setShortcut('')
        self.file_open.setStatusTip('打开备案比对结果')
        self.file_Menu.addAction(self.file_open)

        self.select_Menu = self.menubar.addMenu("选择")

        self.select_backup = QAction(QIcon('exit.png'), '&备案文件')
        self.select_backup.setShortcut('')
        self.select_backup.setStatusTip('选择备案文件')
        self.select_Menu.addAction(self.select_backup)

        self.select_source = QAction(QIcon('exit.png'), '&待对比文件')
        self.select_source.setShortcut('')
        self.select_source.setStatusTip('选择待对比文件')
        self.select_Menu.addAction(self.select_source)

        self.record_Menu = self.menubar.addMenu("对比记录")

        self.win_Menu = self.menubar.addMenu("窗口")

        self.win_max = QAction(QIcon('exit.png'), '&窗口最大化')
        self.win_max.setShortcut('')
        self.win_max.setStatusTip('最大化窗口')
        self.win_Menu.addAction(self.win_max)

        self.win_min = QAction(QIcon('exit.png'), '&窗口最小化')
        self.win_min.setShortcut('')
        self.win_min.setStatusTip('最小化窗口')
        self.win_Menu.addAction(self.win_min)

        self.user_Menu = self.menubar.addMenu("用户")

        self.user_out = QAction(QIcon('exit.png'), '&用户信息')
        self.user_out.setShortcut('')
        self.user_out.setStatusTip('注销用户')
        self.user_Menu.addAction(self.user_out)

        #     self.user_out.triggered.connect(self.sign_out)
        #
        # def sign_out(self):
        #     self.close()
        #     dialog = logindialog()
        #     if dialog.exec_() == QDialog.Accepted:
        #         the_window = Main()
        #         self.windowList.append(the_window)  # 这句一定要写,不然无法重新登录
        #         the_window.show()

        self.quit_Menu = self.menubar.addMenu("退出")

        self.quit_app = QAction(QIcon('exit.png'), '&退出')
        self.quit_app.setShortcut('Ctrl+Q')
        self.quit_app.setStatusTip('退出')
        self.quit_Menu.addAction(self.quit_app)

        self.help_Menu = self.menubar.addMenu("帮助")
        self.help_app = QAction(QIcon('exit.png'), '&帮助')
        self.help_app.setShortcut('')
        self.help_app.setStatusTip('帮助信息')
        self.help_Menu.addAction(self.help_app)

        self.groupbox_1 = QGroupBox('备案文件')  # 1
        # self.groupbox_1.setMaximumSize(9999,9999)
        self.groupbox_2 = QGroupBox('待对比文件')
        # self.groupbox_2.setMaximumSize(9999,9999)
        self.groupbox_3 = QGroupBox('比对结果')
        self.groupbox_4 = QGroupBox()
        self.groupbox_4.setLayout(self.h5_layout)
        self.h11_layout.addWidget(self.groupbox_4)
        self.toolbutton = QtWidgets.QToolButton()
        self.toolbar.setMovable(False)
        self.toolbutton.setAutoRaise(True)
        self.toolbutton.setIcon(QIcon('素材/开始.png'))
        self.toolbutton.setText("开始")
        self.toolbutton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.toolbutton2 = QtWidgets.QToolButton()
        # self.toolbutton2.setCheckable(False)
        self.toolbutton2.setAutoRaise(True)
        self.toolbutton2.setIcon(QIcon('素材/文档.png'))
        self.toolbutton2.setText("保存")
        self.toolbutton2.setToolTip("保存比对结果")
        # 在工具栏ToolBar里同时添加图标和文字,并设置图标和文字的相对位置;若没有下面的一行或多行代码,则只显示图标或文字。
        self.toolbutton2.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.comboBox = QtWidgets.QComboBox()
        self.comboBox.addItem("")
        self.comboBox.addItem("")

        self.toolbutton3 = QtWidgets.QToolButton()
        # self.toolbutton3.setCheckable(False)
        self.toolbutton3.setAutoRaise(True)
        self.toolbutton3.setIcon(QIcon('素材/关闭.png'))
        self.toolbutton3.setText("退出")
        self.toolbutton3.setToolTip("退出")
        # 在工具栏ToolBar里同时添加图标和文字,并设置图标和文字的相对位置;若没有下面的一行或多行代码,则只显示图标或文字。
        self.toolbutton3.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.toolbutton4 = QtWidgets.QToolButton()
        # self.toolbutton3.setCheckable(False)
        self.toolbutton4.setAutoRaise(True)
        self.toolbutton4.setIcon(QIcon('素材/下载.png'))
        self.toolbutton4.setText("下载备案")
        self.toolbutton4.setToolTip("下载备案文件")
        # 在工具栏ToolBar里同时添加图标和文字,并设置图标和文字的相对位置;若没有下面的一行或多行代码,则只显示图标或文字。
        self.toolbutton4.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.toolbutton5 = QtWidgets.QToolButton()
        # self.toolbutton3.setCheckable(False)
        self.toolbutton5.setAutoRaise(True)
        self.toolbutton5.setIcon(QIcon('素材/上传.png'))
        self.toolbutton5.setText("上传结果")
        self.toolbutton5.setToolTip("上传代码比对结果")
        # 在工具栏ToolBar里同时添加图标和文字,并设置图标和文字的相对位置;若没有下面的一行或多行代码,则只显示图标或文字。
        self.toolbutton5.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.toolbar.addWidget(self.toolbutton)
        self.toolbar.addSeparator()
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.toolbutton4)
        self.toolbar.addSeparator()
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.comboBox)
        self.toolbar.addSeparator()
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.toolbutton2)
        self.toolbar.addSeparator()
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.toolbutton5)
        self.toolbar.addSeparator()
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.toolbutton3)

        self.backup_label = QtWidgets.QLabel()
        self.backup_label.setFixedSize(375, 25)
        self.backup_label.setFont(QFont(
            "Roman times",
            11,
        ))
        self.backup_label.setText("请选择合适的备案文件")

        self.backup_button = QtWidgets.QPushButton()
        self.backup_button.setFixedSize(30, 30)
        self.backup_button.setIcon(QIcon("素材/文件夹.png"))

        self.source_label = QtWidgets.QLabel()
        self.source_label.setFixedSize(375, 25)
        self.source_label.setFont(QFont(
            "Roman times",
            11,
        ))
        self.source_label.setText("请选择合适的待比对文件")

        self.source_button = QtWidgets.QPushButton()
        self.source_button.setFixedSize(30, 30)
        self.source_button.setIcon(QIcon("素材/文件夹.png"))

        self.h6_layout.addWidget(self.backup_label)
        self.h6_layout.addWidget(self.backup_button)
        self.h6_layout.addWidget(self.source_label)
        self.h6_layout.addWidget(self.source_button)

        self.backup_win = QtWidgets.QWidget()
        self.backup_win.setFixedSize(420, 300)
        # self.backup_win.resize(500, 300)
        # self.backup_win.setMaximumSize(9999,9999)
        # self.backup_win.resize(420,300)

        self.source_win = QtWidgets.QWidget()
        self.source_win.setFixedSize(420, 300)
        # self.source_win.setMaximumSize(9999,9999)

        self.h1_layout.addWidget(self.backup_win)
        self.groupbox_1.setLayout(self.h1_layout)
        self.h2_layout.addWidget(self.source_win)
        self.groupbox_2.setLayout(self.h2_layout)

        self.backup_model = QFileSystemModel()

        self.backup_tree = QTreeView(self.backup_win)

        self.backup_model.setReadOnly(True)
        self.backup_tree.setGeometry(0, 0, 400, 290)

        self.source_model = QFileSystemModel()

        self.source_tree = QTreeView(self.source_win)

        self.source_model.setReadOnly(True)
        self.source_tree.setGeometry(0, 0, 400, 290)

        self.textBrowser = QtWidgets.QTextBrowser()

        self.textBrowser.setFixedSize(800, 250)
        self.textBrowser.setMaximumSize(9999, 9999)
        self.h7_layout.addWidget(self.textBrowser)
        self.groupbox_3.setLayout(self.h7_layout)
        self.pbar = QtWidgets.QProgressBar()
        self.pbar.setAlignment(Qt.AlignLeading | Qt.AlignLeft
                               | Qt.AlignVCenter)
        self.h9_layout.addWidget(self.pbar)
        # self.statusbar = QtWidgets.QStatusBar()
        self.h10_layout.addWidget(self.statusbar)

        self.h3_layout.addWidget(self.groupbox_1)
        self.h3_layout.addWidget(self.groupbox_2)
        # self.h3_layout.setSpacing(0)
        self.h8_layout.addWidget(self.groupbox_3)
        self.all_v_layout.addLayout(self.h4_layout)
        self.all_v_layout.addLayout(self.h11_layout)
        self.all_v_layout.addLayout(self.h6_layout)
        self.all_v_layout.addLayout(self.h3_layout)
        self.all_v_layout.addLayout(self.h8_layout)
        self.all_v_layout.addLayout(self.h9_layout)
        self.all_v_layout.addLayout(self.h10_layout)
        windget.setLayout(self.all_v_layout)
        self.retranslateUi(windget)

    def retranslateUi(self, windget):
        _translate = QtCore.QCoreApplication.translate
        windget.setWindowTitle(_translate("MainWindow", "电表代码对比软件"))
        windget.setWindowIcon(QIcon('素材/电网.ico'))
        self.comboBox.setItemText(0, _translate("MainWindow", "直接对比方式"))
        self.comboBox.setItemText(1, _translate("MainWindow", "数字签名对比方式"))
示例#20
0
class MyTreeView(QTreeView):
    # Overwritten
    def __init__(self, main):
        super().__init__()
        self.main = main

        self.model = QFileSystemModel()
        current_path = os.path.abspath(os.getcwd())
        self.model.setRootPath(current_path)
        self.setModel(self.model)
        self.setRootIndex(self.model.index(current_path))
        self.setColumnWidth(0, 250)
        self.setSortingEnabled(True)
        self.sortByColumn(0, 0)

        self.setEditTriggers(QTreeView.NoEditTriggers)
        self.model.setReadOnly(False)

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.context_menu)

    #   ___         _           _   __  __
    #  / __|___ _ _| |_ _____ _| |_|  \/  |___ _ _ _  _
    # | (__/ _ \ ' \  _/ -_) \ /  _| |\/| / -_) ' \ || |
    #  \___\___/_||_\__\___/_\_\\__|_|  |_\___|_||_\_,_|
    def context_menu(self):
        menu = QMenu()

        open_ = menu.addAction("Open / Display")
        open_.triggered.connect(self.c_m_open)

        web = menu.addAction("Load webView file")
        web.triggered.connect(self.c_m_web_load)

        menu.addSeparator()

        rename = menu.addAction("Rename")
        rename.triggered.connect(self.c_m_rename)

        copy_path = menu.addAction("Copy path")
        copy_path.triggered.connect(self.c_m_copy_path)

        duplicate = menu.addAction("Duplicate")
        duplicate.triggered.connect(self.c_m_duplicate)

        show_in_explorer = menu.addAction("Show in explorer")
        show_in_explorer.triggered.connect(self.c_m_explorer)

        menu.addSeparator()

        delete = menu.addAction("Delete")
        delete.triggered.connect(self.c_m_delete)

        cursor = QCursor()
        menu.exec_(cursor.pos())

    def c_m_open(self):
        """"Abre un archivo o despliega un fichero"""
        index = self.currentIndex()
        path = self.model.filePath(index)
        if os.path.isfile(path):
            self.main.open_file(path)
        else:
            self.setExpanded(index, True)

    def c_m_web_load(self):
        """Abre en el webViewer el fichero"""
        index = self.currentIndex()
        path = self.model.filePath(index)
        if os.path.isfile(path):
            self.main.webView.update_by_file(path)
        else:
            pass

    def c_m_rename(self):
        """"Renombrar archivo o directorio desde el TreeView"""
        index = self.currentIndex()
        self.edit(index)

    def c_m_copy_path(self):
        """"Copia la ruta de un archivo o directorio"""
        index = self.currentIndex()
        path = self.model.filePath(index)
        pyperclip.copy(path)

    def c_m_duplicate(self):
        """"Duplica un archivo o directorio"""
        index = self.currentIndex()
        path = self.model.filePath(index)
        if os.path.isfile(path):
            filename, file_extension = os.path.splitext(path)
            copyfile(path, f"{filename}(copy){file_extension}")
        else:
            copytree(path, path + "(copy)")

    def c_m_explorer(self):
        """"Abre el explorador en el path padre de un archivo o directorio"""
        index = self.currentIndex()
        path = self.model.filePath(index)
        path = os.path.realpath(path)
        path = os.path.dirname(path)
        os.startfile(path)

    def c_m_delete(self):
        """"Borra un archivo o directorio (lo manda a la papelera de reciclaje)"""
        index = self.currentIndex()
        path = self.model.filePath(index)
        path = os.path.realpath(path)
        # if os.path.isfile(path):
        #     os.remove(path)
        # else:
        #     rmtree(path)
        qm = QMessageBox
        ret = qm.question(
            self,
            '',
            f"Are you sure to delete '{os.path.basename(path)}' ?",
            qm.Yes | qm.No,
            defaultButton=qm.No)
        if ret == qm.Yes:
            send2trash(path)
示例#21
0
class main(QMainWindow, DiskCleaner_ui.Ui_MainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi(self)

        self.openMenu()

        systray_icon = QIcon("DC.png")
        self.systray = QSystemTrayIcon(systray_icon, self)
        self.systray.setContextMenu(self.menu)
        self.systray.show()
        self.systray.showMessage("DC", "Started...",
                                 QSystemTrayIcon.Information)
        self.closeapp.triggered.connect(self.close)

        self.setWindowIcon(systray_icon)

        self.Duplicate()
        self.dormant()
        self.Temp()

    def closeEvent(self, event):
        reply = QMessageBox.question(self, 'Exit',
                                     "Are you sure you want to exit?",
                                     QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def scan(self):
        if os.listdir(self.temp_path) or os.listdir(self.dormant_path) == []:
            self.systray.showMessage("DC", "No Temporary files..",
                                     QSystemTrayIcon.Information)
        else:
            pass

    def clear_Files(self):
        reply = QMessageBox.question(
            self, 'Clear Files', "Are you sure you want delete all files?",
            QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            try:
                self.scan()
                with os.scandir(self.temp_path) or os.scandir(
                        self.dormant_path) as entries:
                    for entry in entries:
                        if entry.is_file() or entry.is_symlink():
                            os.remove(entry.path)
                            self.systray.showMessage(
                                "DC", "Temporary files/folders cleared",
                                QSystemTrayIcon.Information)
                        elif entry.is_dir():
                            shutil.rmtree(entry.path)
                            self.systray.showMessage(
                                "DC", "Temporary files/folders cleared",
                                QSystemTrayIcon.Information)
                        else:
                            pass
            except Exception:
                pass

    def openMenu(self):
        self.menu = QMenu()
        self.restore = QAction("Restore", self)
        self.closeapp = QAction("Close", self)

        self.menu.addActions([self.restore, self.closeapp])

    def on_clicked(self, index):
        self.path = self.fileSystemModel.filePath(index)
        print(self.path)

    def zip_file(self):
        try:
            if os.path.exists(self.path):
                try:
                    dask = QFileDialog.getSaveFileName(
                        self, 'Select Folder to store Zip file',
                        expanduser("~"), '.zip')
                    dpath = str(dask[0])
                    if os.path.isfile(self.path):
                        with ZipFile(dpath, 'w') as zip:
                            zip.write(self.path, basename(self.path))

                            self.systray.showMessage(
                                "DC", "File Zipped succesfully",
                                QSystemTrayIcon.Information)
                    else:
                        zf = zipfile.ZipFile(dpath, "w")
                        for dirname, subdirs, files in os.walk(self.path):
                            zf.write(dirname, basename(dirname))
                            for filename in files:
                                zf.write(
                                    os.path.join(dirname, filename),
                                    basename(os.path.join(dirname, filename)))
                        zf.close()
                        self.systray.showMessage("DC",
                                                 "Folder Zipped Succesfully",
                                                 QSystemTrayIcon.Information)
                except Exception:
                    pass
            else:
                pass
        except Exception:
            pass

    def delete_file(self):
        reply = QMessageBox.question(self, 'Delete File',
                                     "Are you sure you want to delete file?",
                                     QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            try:
                if os.path.exists(self.path):
                    try:
                        os.remove(self.path)
                        self.systray.showMessage("DC",
                                                 "Temporary  file Deleted",
                                                 QSystemTrayIcon.Information)
                    except Exception:
                        shutil.rmtree(self.path)
                        self.systray.showMessage("DC",
                                                 "Temporary  folder Deleted",
                                                 QSystemTrayIcon.Information)
            except Exception:
                self.systray.showMessage("DC", "Error deleting file",
                                         QSystemTrayIcon.Critical)
        else:
            pass

    def tabMenu(self, position):

        self.tmenu = QMenu()

        self.open = self.tmenu.addAction('Open')
        self.open_file_location = self.tmenu.addAction('Open File Location')

        self.tmenu.addActions([self.open, self.open_file_location])
        action = self.tmenu.exec_(
            self.temp_treeView.viewport().mapToGlobal(position))

        if action == self.open:
            os.startfile(self.path, 'open')
        elif action == self.open_file_location:
            try:
                subprocess.Popen(r'explorer /select,' +
                                 "{}".format(self.path).replace('/', '\\'))
            except Exception:
                pass

    def Temp(self):
        self.temp_treeView = QTreeView()

        self.temp_treeView.setContextMenuPolicy(Qt.CustomContextMenu)
        self.temp_treeView.customContextMenuRequested.connect(self.tabMenu)

        self.fileSystemModel = QFileSystemModel(self.temp_treeView)
        self.fileSystemModel.setReadOnly(False)
        self.temp_path = expanduser('~') + '\AppData\Local\Temp'
        root = self.fileSystemModel.setRootPath(self.temp_path)
        self.temp_treeView.setModel(self.fileSystemModel)
        self.temp_treeView.setRootIndex(root)
        self.temp_treeView.setSortingEnabled(True)

        self.temp_treeView.clicked.connect(self.on_clicked)

        self.clearAll_button = QPushButton("Clear all Files")
        self.clearAll_button.setFixedSize(90, 30)

        self.clearAll_button.clicked.connect(self.clear_Files)

        self.temp_delete_button = QPushButton('Delete')
        self.temp_delete_button.setFixedSize(90, 30)

        self.temp_delete_button.clicked.connect(self.delete_file)

        self.temp_zip_button = QPushButton('Zip file')
        self.temp_zip_button.setFixedSize(90, 30)

        self.temp_zip_button.clicked.connect(self.zip_file)

        Layout = QHBoxLayout(self)
        Layout.addWidget(self.clearAll_button)
        Layout.addWidget(self.temp_delete_button)
        Layout.addWidget(self.temp_zip_button)
        Layout.addWidget(self.temp_treeView)

        self.Temp_Tab.setLayout(Layout)

    def Duplicate(self):

        dup_button = QPushButton('Duplicate Finder')
        dup_button.setFixedSize(90, 30)

        Layout = QHBoxLayout(self)
        Layout.addWidget(dup_button)

        dup_button.clicked.connect(self.dup_finder)

        self.Duplicate_Tab.setLayout(Layout)

    def dup_finder(self):
        def chunk_reader(fobj, chunk_size=2048):
            """ Generator that reads a file in chunks of bytes """
            while True:
                chunk = fobj.read(chunk_size)
                if not chunk:
                    return
                yield chunk

        class SignalHelper(QObject):
            error = pyqtSignal(tuple)
            result = pyqtSignal(object)
            finished = pyqtSignal()
            progress = pyqtSignal(str, str)

        class Worker(QRunnable):
            def __init__(self, fn, *args, **kwargs):
                super(Worker, self).__init__()

                self.fn = fn
                self.args = args
                self.kwargs = kwargs
                self.signals = SignalHelper()

                # Add a callback to our kwargs
                kwargs['progress_callback'] = self.signals.progress

            @pyqtSlot()
            def run(self):
                try:
                    result = self.fn(*self.args, **self.kwargs)
                except:
                    traceback.print_exc()
                    exctype, value = sys.exc_info()[:2]
                    self.signals.error.emit(
                        (exctype, value, traceback.format_exc()))
                else:
                    self.signals.result.emit(result)
                finally:
                    self.signals.finished.emit()

        class MainWindow(QMainWindow):
            def __init__(self, *args, **kwargs):
                super(MainWindow, self).__init__(*args, **kwargs)

                self.setWindowTitle('Duplicate Finder')

                systray_icon = QIcon("s.png")
                self.systray = QSystemTrayIcon(systray_icon, self)
                self.systray.show()

                layout = QVBoxLayout()
                self.textEdit = QTextEdit("Display duplicate files :")
                self.textEdit.setReadOnly(True)

                self.b = QPushButton("Scan files")
                self.b.setCheckable(True)
                self.b.pressed.connect(self.watcher)

                self.d = QPushButton('Delete dup files')
                self.d.clicked.connect(self.delete_duplicate_files)

                layout.addWidget(self.textEdit)
                layout.addWidget(self.b)
                layout.addWidget(self.d)

                w = QWidget()
                w.setLayout(layout)
                self.setCentralWidget(w)

                self.threadpool = QThreadPool()

            def delete_duplicate_files(self):
                def remove_duplicates(dir, hashfun=hashlib.sha512):

                    unique = set()
                    for filename in os.listdir(dir):
                        filepath = os.path.join(dir, filename)
                        if os.path.isfile(filepath):
                            hashobj = hashfun()
                            for chunk in chunk_reader(open(filepath, 'rb')):
                                hashobj.update(chunk)
                                # the size of the hashobj is constant
                            hashfile = hashobj.hexdigest()
                            if hashfile not in unique:
                                unique.add(hashfile)
                            else:
                                try:
                                    os.remove(filepath)
                                    print('delete')

                                except Exception:
                                    print(' cant delete')

                try:
                    reply = QMessageBox.question(
                        self, 'Delete File',
                        "Are you sure you want to delete file?",
                        QMessageBox.Yes | QMessageBox.No)
                    if reply == QMessageBox.Yes:
                        hashfun = hashlib.sha256
                        remove_duplicates(self.path)
                        self.systray.showMessage("DC",
                                                 'Duplicate files deleted',
                                                 QSystemTrayIcon.Information)
                    else:
                        pass
                except IndexError:
                    self.systray.showMessage("DC",
                                             "Error deleting duplicate files",
                                             QSystemTrayIcon.Critical)

            def watcher(self):
                self.path = QFileDialog.getExistingDirectory(
                    self, 'select folder to scan', expanduser('~'))

                worker = Worker(self.check_for_duplicates)
                worker.signals.progress.connect(self.progress_fn)
                self.threadpool.start(worker)

            def progress_fn(self, duplicate, full_path):
                self.textEdit.append(
                    "<font color=red>Duplicate found:</font> %s <b>and</b> %s"
                    % (full_path, duplicate))
                self.textEdit.append("")
                self.textEdit.append("")

            def check_for_duplicates(self,
                                     progress_callback,
                                     hash=hashlib.sha1):
                # specify your path !!!
                hashes = {}
                for dirpath, dirnames, filenames in os.walk(self.path):
                    for filename in filenames:
                        full_path = os.path.join(dirpath,
                                                 filename).replace('/', '\\')
                        # print(full_path)
                        hashobj = hash()
                        for chunk in chunk_reader(open(full_path, 'rb')):
                            hashobj.update(chunk)
                        file_id = (hashobj.digest(),
                                   os.path.getsize(full_path))
                        self.duplicate = hashes.get(file_id, None)
                        if self.duplicate:
                            progress_callback.emit(self.duplicate, full_path)
                            print("Duplicate found: %s and %s" %
                                  (full_path, self.duplicate))
                            try:
                                print(self.duplicate)
                            except Exception:

                                print('could not delete')
                        else:
                            hashes[file_id] = full_path

                # return duplicate

        global w
        w = MainWindow()
        w.setGeometry(700, 200, 550, 300)
        w.show()

    def dormant(self):

        treeView = QTreeView()

        treeView.setContextMenuPolicy(Qt.CustomContextMenu)
        treeView.customContextMenuRequested.connect(self.tabMenu)

        fileSystemModel = QFileSystemModel(treeView)
        fileSystemModel.setReadOnly(False)
        self.dormant_path = expanduser('~') + '\Documents'
        root = fileSystemModel.setRootPath(self.dormant_path)
        treeView.setModel(fileSystemModel)
        treeView.setRootIndex(root)
        treeView.setSortingEnabled(True)

        treeView.clicked.connect(self.on_clicked)

        dormant_clearAll_button = QPushButton("Clear all Files")
        dormant_clearAll_button.setFixedSize(90, 30)
        self.dormant_delete_button = QPushButton('Delete')
        self.dormant_delete_button.setFixedSize(90, 30)

        self.dormant_delete_button.clicked.connect(self.delete_file)

        dormant_zip_button = QPushButton('Zip file')
        dormant_zip_button.setFixedSize(90, 30)

        dormant_zip_button.clicked.connect(self.zip_file)

        Layout = QHBoxLayout(self)
        Layout.addWidget(dormant_clearAll_button)
        Layout.addWidget(self.dormant_delete_button)
        Layout.addWidget(dormant_zip_button)
        Layout.addWidget(treeView)

        #dormant_clearAll_button.clicked.connect(self.clear_Files())

        self.UnUsed_Tab.setLayout(Layout)
示例#22
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.isBag = False
        self.currentPath = None
        self.bagConfigFilePath = DEFAULT_CONFIG_FILE
        self.bagKeychainFilePath = DEFAULT_KEYCHAIN_FILE
        self.ui = MainWindowUI()
        self.ui.setup_ui(self)
        self.ui.logTextBrowser.widget.log_update_signal.connect(self.updateLog)
        self.ui.logTextBrowser.setFormatter(
            logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        logging.getLogger().addHandler(self.ui.logTextBrowser)
        logging.getLogger().setLevel(logging.INFO)

        self.fileSystemModel = QFileSystemModel()
        self.fileSystemModel.setReadOnly(False)
        root = self.fileSystemModel.setRootPath(
            self.fileSystemModel.myComputer())
        self.ui.treeView.setModel(self.fileSystemModel)
        self.ui.treeView.setRootIndex(root)
        self.ui.treeView.setAnimated(True)
        self.ui.treeView.setAcceptDrops(True)
        self.ui.treeView.setColumnWidth(0, 300)

        self.enableControls()

    def checkIfBag(self):
        if not self.currentPath:
            self.isBag = False
        else:
            if os.path.isdir(self.currentPath):
                QApplication.setOverrideCursor(Qt.WaitCursor)
                self.isBag = bdb.is_bag(self.currentPath)
                QApplication.restoreOverrideCursor()
                if self.isBag:
                    self.updateStatus(
                        "The directory [%s] is a bag." % self.currentPath,
                        True)
                else:
                    self.updateStatus(
                        "The directory [%s] is NOT a bag." % self.currentPath,
                        False)
            else:
                self.isBag = False

    def disableControls(self):
        self.ui.actionCancel.setEnabled(True)
        self.ui.treeView.setEnabled(False)
        self.ui.actionCreateOrUpdate.setEnabled(False)
        self.ui.actionRevert.setEnabled(False)
        self.ui.actionFetchMissing.setEnabled(False)
        self.ui.actionFetchAll.setEnabled(False)
        self.ui.actionValidateFast.setEnabled(False)
        self.ui.actionValidateFull.setEnabled(False)
        self.ui.actionArchiveZIP.setEnabled(False)
        self.ui.actionArchiveTGZ.setEnabled(False)

    def enableControls(self):
        self.ui.treeView.setEnabled(True)
        self.ui.toggleCreateOrUpdate(self)
        self.ui.actionCreateOrUpdate.setEnabled(
            os.path.isdir(self.currentPath) if self.currentPath else False)
        self.ui.actionRevert.setEnabled(self.isBag)
        self.ui.actionFetchMissing.setEnabled(self.isBag)
        self.ui.actionFetchAll.setEnabled(self.isBag)
        self.ui.actionValidateFast.setEnabled(self.isBag)
        self.ui.actionValidateFull.setEnabled(self.isBag)
        self.ui.actionArchiveZIP.setEnabled(self.isBag)
        self.ui.actionArchiveTGZ.setEnabled(self.isBag)
        self.ui.actionCancel.setEnabled(False)

    def closeEvent(self, event):
        self.cancelTasks()
        event.accept()

    def cancelTasks(self):
        self.disableControls()
        async_task.Request.shutdown()
        self.statusBar().showMessage(
            "Waiting for background tasks to terminate...")

        while True:
            qApp.processEvents()
            if QThreadPool.globalInstance().waitForDone(10):
                break

        self.statusBar().showMessage(
            "All background tasks terminated successfully")

    @pyqtSlot()
    def bagTaskTriggered(self):
        self.ui.progressBar.reset()
        self.ui.logTextBrowser.widget.clear()
        self.disableControls()

    @pyqtSlot(str)
    def updateStatus(self, status, success=True):
        if success:
            logging.info(status)
        else:
            logging.error(status)
        self.statusBar().showMessage(status)

    @pyqtSlot(str, bool)
    def updateUI(self, status, success=True):
        self.updateStatus(status, success)
        self.enableControls()

    @pyqtSlot(str)
    def updateLog(self, text):
        self.ui.logTextBrowser.widget.appendPlainText(text)

    @pyqtSlot(int, int)
    def updateProgress(self, current, maximum):
        self.ui.progressBar.setRange(1, maximum)
        self.ui.progressBar.setValue(current)
        self.ui.progressBar.repaint()

    @pyqtSlot(str, bool, bool)
    def onBagCreated(self, status, success, is_update):
        self.isBag = True if is_update else success
        self.updateUI(status, success)

    @pyqtSlot(str, bool)
    def onBagReverted(self, status, success):
        self.isBag = not success
        self.updateUI(status, success)

    @pyqtSlot(bool)
    def on_actionCreateOrUpdate_triggered(self):
        if not self.currentPath:
            return
        self.bagTaskTriggered()
        createOrUpdateTask = bag_tasks.BagCreateOrUpdateTask()
        createOrUpdateTask.status_update_signal.connect(self.onBagCreated)
        createOrUpdateTask.createOrUpdate(self.currentPath, self.isBag,
                                          self.bagConfigFilePath)

    @pyqtSlot(bool)
    def on_actionRevert_triggered(self):
        if not self.currentPath:
            return

        msg = QMessageBox()
        msg.setIcon(QMessageBox.Warning)
        msg.setWindowTitle("Confirm Action")
        msg.setText("Are you sure you want to revert this bag directory?")
        msg.setInformativeText(
            "Reverting a bag directory will cause all manifests to be deleted including fetch.txt, "
            "if present.\n\nIf a bag contains remote file references, these files will no longer be "
            "resolvable.\n\nIt is recommended that you either resolve any remote files prior to "
            "reverting such a bag, or make a backup copy of it first.")
        msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        ret = msg.exec_()
        if ret == QMessageBox.Cancel:
            return

        self.bagTaskTriggered()
        revertTask = bag_tasks.BagRevertTask()
        revertTask.status_update_signal.connect(self.onBagReverted)
        revertTask.revert(self.currentPath)

    @pyqtSlot(bool)
    def on_actionArchiveZIP_triggered(self):
        if not self.currentPath:
            return
        self.bagTaskTriggered()
        archiveTask = bag_tasks.BagArchiveTask()
        archiveTask.status_update_signal.connect(self.updateUI)
        archiveTask.archive(self.currentPath, "zip")
        self.updateStatus("Archive (ZIP) initiated for bag: [%s]" %
                          self.currentPath)

    @pyqtSlot(bool)
    def on_actionArchiveTGZ_triggered(self):
        if not self.currentPath:
            return
        self.bagTaskTriggered()
        archiveTask = bag_tasks.BagArchiveTask()
        archiveTask.status_update_signal.connect(self.updateUI)
        archiveTask.archive(self.currentPath, "tgz")
        self.updateStatus("Archive (TGZ) initiated for bag: [%s]" %
                          self.currentPath)

    @pyqtSlot(bool)
    def on_actionValidateFast_triggered(self):
        if not self.currentPath:
            return
        self.bagTaskTriggered()
        validateTask = bag_tasks.BagValidateTask()
        validateTask.status_update_signal.connect(self.updateUI)
        validateTask.validate(self.currentPath, True, self.bagConfigFilePath)

    @pyqtSlot(bool)
    def on_actionValidateFull_triggered(self):
        if not self.currentPath:
            return
        self.bagTaskTriggered()
        validateTask = bag_tasks.BagValidateTask()
        validateTask.status_update_signal.connect(self.updateUI)
        validateTask.progress_update_signal.connect(self.updateProgress)
        validateTask.validate(self.currentPath, False, self.bagConfigFilePath)
        self.updateStatus(
            "Full validation initiated for bag: [%s] -- Please wait..." %
            self.currentPath)

    @pyqtSlot(bool)
    def on_actionFetchAll_triggered(self):
        if not self.currentPath:
            return
        self.bagTaskTriggered()
        fetchTask = bag_tasks.BagFetchTask()
        fetchTask.status_update_signal.connect(self.updateUI)
        fetchTask.progress_update_signal.connect(self.updateProgress)
        fetchTask.fetch(self.currentPath, True, self.bagKeychainFilePath,
                        self.bagConfigFilePath)
        self.updateStatus(
            "Fetch all initiated for bag: [%s] -- Please wait..." %
            self.currentPath)

    @pyqtSlot(bool)
    def on_actionFetchMissing_triggered(self):
        if not self.currentPath:
            return
        self.bagTaskTriggered()
        fetchTask = bag_tasks.BagFetchTask()
        fetchTask.status_update_signal.connect(self.updateUI)
        fetchTask.progress_update_signal.connect(self.updateProgress)
        fetchTask.fetch(self.currentPath, False, self.bagKeychainFilePath,
                        self.bagConfigFilePath)
        self.updateStatus(
            "Fetch missing initiated for bag: [%s] -- Please wait..." %
            self.currentPath)

    @pyqtSlot(QModelIndex)
    def on_treeView_clicked(self, index):
        self.ui.statusBar.clearMessage()
        self.ui.logTextBrowser.widget.clear()
        self.currentPath = os.path.normpath(
            os.path.abspath(
                self.fileSystemModel.filePath(
                    self.fileSystemModel.index(index.row(), 0,
                                               index.parent()))))
        self.checkIfBag()
        self.enableControls()

    @pyqtSlot(bool)
    def on_actionOptions_triggered(self):
        options_window.OptionsDialog.getOptions(self)

    @pyqtSlot(bool)
    def on_actionCancel_triggered(self):
        self.cancelTasks()
        self.ui.progressBar.reset()
        self.enableControls()

    @pyqtSlot()
    def on_actionAbout_triggered(self):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Information)
        msg.setWindowTitle("About BDBag GUI")
        msg.setText("Version Information")
        msg.setInformativeText("BDBag GUI: %s\nBDBag: %s\nBagit: %s\n" %
                               (VERSION, BDBAG_VERSION, BAGIT_VERSION))
        msg.setStandardButtons(QMessageBox.Ok)
        ret = msg.exec_()
示例#23
0
class PACSWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.left = 10
        self.top = 10
        self.width = 800
        self.height = 650
        self.leftPanelWidth = 250
        self.imageToView = pyqtSignal()

        self.initUI()

    def initUI(self):
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.model = QFileSystemModel()
        self.model.setRootPath(r'C:\dcmtk')
        self.model.setReadOnly(True)

        self.files_view = self.__initFileTreeView(self.model)
        self.files_view.doubleClicked.connect(self.storeItem)

        self.pacs_model = PacsItemModel(["ID", "Name", "Birth"])

        if PACS_Action.isConnect():
            try:
                patients = PACS_Action.find_patients()
                self.pacs_model.update(patients)
            except:
                print('Error on loading patients list')

        self.pacs_view = PACSView()
        self.pacs_view.setModel(self.pacs_model)
        self.pacs_view.setMinimumWidth(200)
        self.pacs_view.setSizeAdjustPolicy(
            QAbstractScrollArea.AdjustToContents)
        self.pacs_view.horizontalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.pacs_view.resizeColumnsToContents()
        self.pacs_view.doubleClicked.connect(self.showImage)

        splitter = QSplitter()
        splitter.addWidget(self.files_view)
        splitter.addWidget(self.pacs_view)

        layout = QHBoxLayout()
        layout.addWidget(splitter)

        self.setLayout(layout)

    def storeItem(self, index):
        path = self.model.filePath(index)
        response = PACS_Action.storeDICOM(str(path))
        if response:
            self.pacs_model.update(PACS_Action.find_patients())
            self.pacs_model.layoutChanged.emit()
            self.pacs_view.setModel(self.pacs_model)
            QMessageBox.information(
                self, 'Store Success',
                'File {0} stored succesful to PACS'.format(str(path)),
                QMessageBox.Ok)

            return response
        else:
            QMessageBox.critical(
                self, 'Store failed',
                'File {0} is not stored to PACS'.format(str(path)),
                QMessageBox.Ok)
            return response

    def showImage(self):
        path = self.pacs_view.get_path_image()

    def __initFileTreeView(self, model):
        treeView = QTreeView()
        treeView.setModel(model)
        treeView.setRootIndex(model.index(r'C:'))
        treeView.hideColumn(1)
        treeView.hideColumn(3)
        treeView.setAnimated(True)
        treeView.setIndentation(20)
        treeView.setSortingEnabled(True)
        treeView.setMinimumWidth(100)

        return treeView

    def updataPatients(self):
        if PACS_Action.isConnect():
            try:
                patients = PACS_Action.find_patients()
                self.pacs_model.update(patients)
                self.pacs_view.update()
            except:
                print('Error on loading patients list')
示例#24
0
class FileSystemTable(QTableView, TableType):
    Q_ENUMS(TableType)

    transferFileRequest = pyqtSignal(str)
    rootChanged = pyqtSignal(str)

    def __init__(self, parent=None):
        super(FileSystemTable, self).__init__(parent)

        self._table_type = TableType.Local

        # This prevents doing unneeded initialization
        # when QtDesginer loads the plugin.
        if parent is None:
            return

        self.parent = parent
        self.path_data = dict()
        self.doubleClicked.connect(self.changeRoot)
        self.selected_row = None
        self.clipboard = QApplication.clipboard()

        self.model = QFileSystemModel()
        self.model.setReadOnly(True)
        self.model.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot
                             | QDir.AllEntries)

        self.setModel(self.model)

        self.verticalHeader().hide()
        self.horizontalHeader().setStretchLastSection(True)
        self.setAlternatingRowColors(True)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.info = Info()
        self._nc_file_dir = self.info.getProgramPrefix()
        self.setRootPath(self._nc_file_dir)

    def showEvent(self, event=None):
        self.rootChanged.emit(self._nc_file_dir)

    def changeRoot(self, index):

        path = self.model.filePath(self.rootIndex())
        new_path = self.model.filePath(index)

        absolute_path = os.path.join(path, new_path)

        file_info = QFileInfo(absolute_path)
        if file_info.isDir():
            self.model.setRootPath(absolute_path)
            self.setRootIndex(self.model.index(absolute_path))

            self.rootChanged.emit(absolute_path)

    @pyqtSlot()
    def newFile(self):
        path = self.model.filePath(self.rootIndex())
        new_file = QFile(os.path.join(path, "New File"))
        new_file.open(QIODevice.ReadWrite)

    @pyqtSlot()
    def deleteFile(self):
        index = self.selectionModel().currentIndex()
        path = self.model.filePath(index)
        if path:
            fileInfo = QFileInfo(path)
            if fileInfo.isFile():
                if not self.ask_dialog(
                        "Do you wan't to delete the selected file?"):
                    return
                file = QFile(path)
                file.remove()

            elif fileInfo.isDir():
                if not self.ask_dialog(
                        "Do you wan't to delete the selected directory?"):
                    return
                directory = QDir(path)
                directory.removeRecursively()

    @pyqtSlot()
    def createDirectory(self):
        path = self.model.filePath(self.rootIndex())
        directory = QDir()
        directory.setPath(path)
        directory.mkpath("New Folder")

    @pyqtSlot(str)
    def setRootPath(self, root_path):

        self.rootChanged.emit(root_path)
        self.model.setRootPath(root_path)
        self.setRootIndex(self.model.index(root_path))

        return True

    @pyqtSlot()
    def goUP(self):

        path = self.model.filePath(self.rootIndex())

        file_info = QFileInfo(path)
        directory = file_info.dir()
        new_path = directory.absolutePath()

        currentRoot = self.rootIndex()

        self.model.setRootPath(new_path)
        self.setRootIndex(currentRoot.parent())
        self.rootChanged.emit(new_path)

    @pyqtSlot()
    def doFileTransfer(self):
        index = self.selectionModel().currentIndex()
        path = self.model.filePath(index)
        self.transferFileRequest.emit(path)

    @pyqtSlot(str)
    def transferFile(self, src_path):
        dest_path = self.model.filePath(self.rootIndex())

        src_file = QFile()
        src_file.setFileName(src_path)

        src_file_info = QFileInfo(src_path)

        dst_path = os.path.join(dest_path, src_file_info.fileName())

        src_file.copy(dst_path)

    @pyqtSlot()
    def getSelected(self):
        return self.selected_row

    @pyqtSlot()
    def getCurrentDirectory(self):
        return self.model.rootPath()

    @pyqtProperty(TableType)
    def tableType(self):
        return self._table_type

    @tableType.setter
    def tableType(self, table_type):
        self._table_type = table_type
        if table_type == TableType.Local:
            self.setRootPath(self._nc_file_dir)
        else:
            self.setRootPath('/media/')

    def ask_dialog(self, message):
        box = QMessageBox.question(self.parent, 'Are you sure?', message,
                                   QMessageBox.Yes, QMessageBox.No)
        if box == QMessageBox.Yes:
            return True
        else:
            return False
示例#25
0
class kdFileFinder(QMainWindow):
    def __init__(self):
        super().__init__()
        loadUi(get_file_realpath("kdFileFinder.ui"), self)
        self.setWindowIcon(QIcon(get_file_realpath('data/kdFileFinder.png')))

        self.exception_handler = global_exception_hander()
        self.exception_handler.patch_excepthook()

        self.lw_main.clicked.connect(self.on_lw_main_clicked)
        self.lw_main.doubleClicked.connect(self.on_lw_main_dbclicked)
        self.lw_main.installEventFilter(self)
        self.fileSystemModel = QFileSystemModel(self.lw_main)
        self.fileSystemModel.setReadOnly(True)
        self.fileFilter = self.fileSystemModel.filter()
        self.fileFilter_hidden = None
        home_path = QDir.home().absolutePath()
        self.le_path.setText(home_path)
        root = self.fileSystemModel.setRootPath(home_path)
        self.lw_main.setModel(self.fileSystemModel)
        self.lw_main.setRootIndex(root)
        self.lw_main.setWrapping(True)

        self.le_path.returnPressed.connect(self.on_pb_load_path_clicked)

        self.init_toolbar()
        self.bookmark_list = bookmark.get_bookmark()
        self.init_bookmark()
        self.session_list = set()
        self.last_open_file = set()

        self.isWindowsOS = sys.platform == "win32"
        self.lw_sidebar.itemDoubleClicked.connect(self.on_lw_sidebar_dbclicked)

        self.main_menu = QMenu()
        self.file_menu = QMenu()
        self.folder_menu = QMenu()
        self.toolbar_menu = toolbar_menu()
        self.file_popup_menu = file_menu()

        self.script_manager = script_manager()

    def init_bookmark(self):
        self.lw_sidebar.clear()
        if self.bookmark_list:
            for b in self.bookmark_list:
                self.add_sidebar_item(b)
        self.lw_sidebar.currentItemChanged.connect(self.on_lw_sidebar_clicked)

    def init_drivers(self):
        self.lw_sidebar.clear()
        if self.isWindowsOS:
            drivers = QDir.drives()
            for d in drivers:
                self.add_sidebar_item(d.absoluteFilePath())
        else:
            self.le_path.setText("/")
            self.on_pb_load_path_clicked()
            #             system('x-terminal-emulator --working-directory={} &'.format(self.le_path.text()))
            pass

    def init_session(self):
        print(self.session_list)
        self.lw_sidebar.clear()
        if self.session_list:
            for b in self.session_list:
                self.add_sidebar_item(b)
        self.lw_sidebar.currentItemChanged.connect(self.on_lw_sidebar_clicked)

    def init_toolbar(self):
        self.toolBar.addAction(QIcon(get_file_realpath("data/list-add.png")),
                               "新增")
        self.toolBar.addAction(
            QIcon(get_file_realpath("data/list-remove.png")), "删除")
        self.toolBar.addAction(QIcon(get_file_realpath("data/go-home.png")),
                               "主页")
        self.toolBar.addAction(QIcon(get_file_realpath("data/device.png")),
                               "设备")
        self.toolBar.addAction(
            QIcon(get_file_realpath("data/bookmark-book.png")), "收藏夹")
        self.toolBar.addAction(QIcon(get_file_realpath("data/edit-copy.png")),
                               "标签")
        self.toolBar.addAction(
            QIcon(get_file_realpath("data/history-time.png")), "最近打开的文件")
        self.toolBar.addAction(QIcon(get_file_realpath("data/folder.png")),
                               "显示文件夹").setCheckable(True)
        self.toolBar.addAction(QIcon(get_file_realpath("data/eye.png")),
                               "显示隐藏文件").setCheckable(True)
        self.toolBar.addAction(QIcon(get_file_realpath("data/terminal.png")),
                               "终端")
        self.toolBar.addAction(
            QIcon(get_file_realpath("data/view-list-tree.png")), "我的电脑")
        self.toolBar.addAction(QIcon(get_file_realpath("data/go-up.png")),
                               "返回上层")
        self.toolBar.addAction(QIcon(get_file_realpath("data/menu.png")), "菜单")
        self.toolBar.actionTriggered[QAction].connect(self.on_toolBar_clicked)

    def add_sidebar_item(self, path):
        item = None
        if not basename(path):
            item = QListWidgetItem(path)
        else:
            item = QListWidgetItem(basename(path))
        item.setData(-1, path)
        self.lw_sidebar.addItem(item)

    def go_home(self):
        list1 = QDir.drives()
        for l in list1:
            print(l.absolutePath())

        self.le_path.setText(QDir.home().absolutePath())
        self.on_pb_load_path_clicked()

    def on_toolBar_clicked(self, action):
        action_text = action.text()
        if action_text == "收藏夹":
            self.lb_sidebar.setText(action_text)
            self.init_bookmark()
        elif action_text == "标签":
            self.lb_sidebar.setText(action_text)
            self.init_session()
        elif action_text == "菜单":
            action = self.main_menu.exec_(toolbar_menu.menu_item,
                                          QCursor.pos())
            if action:
                self.toolbar_menu.handle_action(action)
        elif action_text == "最近打开的文件":
            self.lb_sidebar.setText(action_text)
            self.lw_sidebar.clear()
            for f in self.last_open_file:
                self.add_sidebar_item(f)
        elif action_text == "主页":
            self.go_home()
        elif action_text == "终端":
            if self.isWindowsOS:
                chdir(self.le_path.text())
                startfile("cmd.exe")
            else:
                system('x-terminal-emulator --working-directory={} &'.format(
                    self.le_path.text()))
        elif action_text == "设备":
            self.lb_sidebar.setText(action_text)
            self.init_drivers()
        elif action_text == "我的电脑":
            if self.isWindowsOS:
                print("explorer.exe '" + self.le_path.text() + "'")
                try:
                    startfile(self.le_path.text())
#                     system("start C:\Users\bkd")
                except Exception as e:
                    print(str(e))
            else:
                system('xdg-open ' + self.le_path.text())
        elif action_text == "返回上层":
            paren_dir = dirname(self.le_path.text())
            self.le_path.setText(paren_dir)
            self.on_pb_load_path_clicked()
        elif action_text == "显示隐藏文件":
            if action.isChecked():
                self.fileFilter_hidden = QDir.Hidden
                self.fileSystemModel.setFilter(self.fileFilter | QDir.Hidden)
            else:
                self.fileFilter_hidden = None
                self.fileSystemModel.setFilter(self.fileFilter)
        elif action_text == "显示文件夹":
            if action.isChecked():
                if self.fileFilter_hidden:
                    self.fileSystemModel.setFilter(QDir.Dirs | QDir.Hidden
                                                   | QDir.NoDot
                                                   | QDir.NoDotDot)
                else:
                    self.fileSystemModel.setFilter(QDir.Dirs | QDir.NoDot
                                                   | QDir.NoDotDot)
            else:
                self.fileSystemModel.setFilter(self.fileFilter)
        elif action_text == "新增":
            if self.lb_sidebar.text() == "收藏夹":
                self.add_sidebar_item(self.le_path.text())
                kdconfig.list_add("global", "bookmark", self.le_path.text())
            elif self.lb_sidebar.text() == "标签":
                self.session_list.add(self.le_path.text())
                self.add_sidebar_item(self.le_path.text())
                print(self.session_list)
        elif action_text == "删除":
            if self.lb_sidebar.text() == "收藏夹":
                print(self.lw_sidebar.currentRow())
                kdconfig.list_del("global", "bookmark", self.le_path.text())
                self.bookmark_list.discard(self.le_path.text())
                self.lw_sidebar.takeItem(self.lw_sidebar.currentRow())
                print(self.bookmark_list)
            elif self.lb_sidebar.text() == "标签":
                self.session_list.remove(self.le_path.text())

    @pyqtSlot()
    def on_lw_sidebar_clicked(self):
        cur_item = self.lw_sidebar.currentItem()
        if cur_item:
            cur_item_data = cur_item.data(-1)
            if self.lb_sidebar.text() == "最近打开的文件":
                self.statusbar.showMessage(cur_item_data)
            else:
                self.le_path.setText(cur_item_data)
                self.on_pb_load_path_clicked()

    @pyqtSlot()
    def on_lw_sidebar_dbclicked(self):
        cur_item = self.lw_sidebar.currentItem()
        if cur_item:
            cur_item_data = cur_item.data(-1)
            self.statusbar.showMessage(cur_item_data)
            if self.isWindowsOS:
                startfile(cur_item_data)

    @pyqtSlot()
    def on_pb_load_path_clicked(self):
        root = self.fileSystemModel.setRootPath(self.le_path.text())
        self.lw_main.setRootIndex(root)

    def eventFilter(self, qobject, qevent):
        qtype = qevent.type()
        #         print("qtype",qtype)
        #         print("qobject",qobject)
        if qtype == 82:
            counter = len(self.lw_main.selectedIndexes())

            #             右键所在的位置又可能是空白处
            if counter == 1:
                i = self.lw_main.indexAt(QCursor.pos())
                if not i.isValid():
                    print("valid")
                    counter = len(self.lw_main.selectedIndexes())
                else:
                    print("invalid")

#             处理选中的文件
            if counter >= 1:
                action = self.file_menu.exec_(self.file_popup_menu.menu_item,
                                              QCursor.pos())
                if action:
                    file_list = [
                        self.fileSystemModel.itemData(i)[0]
                        for i in self.lw_main.selectedIndexes()
                    ]
                    self.script_manager.run_script(action.text(),
                                                   self.le_path.text(),
                                                   file_list)
#             选中空白处,返回上层目录
            else:
                parent_dir = dirname(self.le_path.text())
                if parent_dir == self.le_path.text() and self.isWindowsOS:
                    pass
                else:
                    self.le_path.setText(parent_dir)
                    self.on_pb_load_path_clicked()
        return False

    @pyqtSlot()
    def on_lw_main_clicked(self):
        #         不连续的多选模式,不处理文件和文件夹,只选中当前项目
        if self.lw_main.selectionMode() == Qt.ControlModifier:
            return

        cur_item_index = self.lw_main.currentIndex()
        cur_item1 = self.fileSystemModel.itemData(cur_item_index)
        cur_item = cur_item1[0]
        print("cur_item", cur_item1)
        sub_path = join(self.le_path.text(), cur_item)
        print("sub_path:" + sub_path)
        if isdir(str(sub_path)):
            print(sub_path + "is a dir")
            self.le_path.setText(sub_path)
            self.on_pb_load_path_clicked()
        elif isfile(str(sub_path)):
            print(sub_path + " is a file")
        else:
            print(type(sub_path))

    @pyqtSlot()
    def on_lw_main_dbclicked(self):
        cur_item_index = self.lw_main.currentIndex()
        cur_item1 = self.fileSystemModel.itemData(cur_item_index)
        cur_item = cur_item1[0]
        sub_path = join(self.le_path.text(), cur_item)
        if isfile(sub_path):
            self.last_open_file.add(sub_path)
            if self.isWindowsOS:
                startfile(sub_path)
            else:
                subprocess.call(["xdg-open", sub_path])
            self.showMinimized()

#     def keyPressEvent(self, event):
#         curKey = event.key()
#         print("按下:" + str(event.key()))
#         if curKey == Qt.Key_M:
#             self.last_open_dir.append(self.le_path)
#             print(self.last_open_dir)
#         return False

    def show_statusbar_msg(self, msg):
        self.statusbar.showMessage(msg)

#     拦截快捷键

    def keyPressEvent(self, event):
        key = event.key()
        print("按下:" + str(event.key()))
        if event.modifiers() == Qt.ControlModifier and key == Qt.Key_C:
            file_list = [
                self.fileSystemModel.itemData(i)[0]
                for i in self.lw_main.selectedIndexes()
            ]
            self.script_manager.run_script("复制", self.le_path.text(),
                                           file_list)
        elif event.modifiers() == Qt.ControlModifier and key == Qt.Key_V:
            self.script_manager.run_script("粘贴", self.le_path.text(), None)
        elif key == Qt.Key_F2:
            file_list = [
                self.fileSystemModel.itemData(self.lw_main.currentIndex())[0]
            ]
            self.script_manager.run_script("重命名", self.le_path.text(),
                                           file_list)
        elif event.modifiers() == Qt.ControlModifier and key == Qt.Key_D:
            self.lb_sidebar.setText("收藏夹")
            self.add_sidebar_item(self.le_path.text())
            kdconfig.list_add("global", "bookmark", self.le_path.text())
        elif event.modifiers() == Qt.ControlModifier and key == Qt.Key_T:
            self.lb_sidebar.setText("标签")
            self.session_list.add(self.le_path.text())
            self.add_sidebar_item(self.le_path.text())
        elif event.modifiers() == Qt.ControlModifier and key == None:
            self.lw_main.setSelectionMode(QAbstractItemView.ExtendedSelection)
            print("duoxuan")
        elif event.modifiers() == Qt.ShiftModifier and key == None:
            self.lw_main.setSelectionMode(
                QAbstractItemView.ContiguousSelection)
            print("shit 多选")
示例#26
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(824, 723)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(":/res/res/mainLogo4.ico"),
                       QtGui.QIcon.Normal, QtGui.QIcon.Off)
        MainWindow.setWindowIcon(icon)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.frame_2 = QtWidgets.QFrame(self.centralwidget)
        self.frame_2.setMinimumSize(QtCore.QSize(200, 265))
        self.frame_2.setMaximumSize(QtCore.QSize(388, 500))
        self.frame_2.setFrameShape(QtWidgets.QFrame.Box)
        self.frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_2.setObjectName("frame_2")
        self.gridLayout_3 = QtWidgets.QGridLayout(self.frame_2)
        self.gridLayout_3.setObjectName("gridLayout_3")
        self.scrollArea_2 = QtWidgets.QScrollArea(self.frame_2)
        self.scrollArea_2.setWidgetResizable(True)
        self.scrollArea_2.setObjectName("scrollArea_2")
        self.scrollAreaWidgetContents_2 = QtWidgets.QWidget()
        self.scrollAreaWidgetContents_2.setGeometry(
            QtCore.QRect(0, 0, 178, 270))
        self.scrollAreaWidgetContents_2.setObjectName(
            "scrollAreaWidgetContents_2")
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout(
            self.scrollAreaWidgetContents_2)
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        # self.listWidget_3 = QtWidgets.QListWidget(self.scrollAreaWidgetContents_2)
        # self.listWidget_3.setObjectName("listWidget_3")
        self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2)
        self.gridLayout_3.addWidget(self.scrollArea_2, 1, 0, 1, 1)
        self.label_2 = QtWidgets.QLabel(self.frame_2)
        self.label_2.setObjectName("label_2")
        self.gridLayout_3.addWidget(self.label_2, 0, 0, 1, 1)
        self.gridLayout.addWidget(self.frame_2, 2, 0, 1, 1)
        self.frame = QtWidgets.QFrame(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(
            QtWidgets.QSizePolicy.MinimumExpanding,
            QtWidgets.QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frame.sizePolicy().hasHeightForWidth())
        self.frame.setSizePolicy(sizePolicy)
        self.frame.setMinimumSize(QtCore.QSize(200, 265))
        self.frame.setMaximumSize(QtCore.QSize(388, 500))
        self.frame.setFrameShape(QtWidgets.QFrame.Box)
        self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame.setObjectName("frame")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.frame)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.scrollArea = QtWidgets.QScrollArea(self.frame)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 178, 270))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.horizontalLayout_5 = QtWidgets.QHBoxLayout(
            self.scrollAreaWidgetContents)
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.listWidget = QtWidgets.QListWidget(
            self.scrollAreaWidgetContents_2)
        self.listWidget.setObjectName("listWidget")
        self.model = QFileSystemModel()
        self.model.setRootPath("D:\Work\PatrolGIS\PatrolGis")
        self.model.setReadOnly(False)
        self.view = QtWidgets.QTreeView(self.scrollAreaWidgetContents)
        self.view.setModel(self.model)
        self.view.setRootIndex(self.model.index("../"))
        self.view.setDragEnabled(True)
        self.view.setDragDropMode(QAbstractItemView.InternalMove)
        # self.view.setEditTriggers(QAbstractItemView.OnViewport(self.canvas))
        self.horizontalLayout_4.addWidget(self.listWidget)
        self.horizontalLayout_5.addWidget(self.view)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.gridLayout_2.addWidget(self.scrollArea, 1, 0, 1, 1)
        self.label = QtWidgets.QLabel(self.frame)
        self.label.setObjectName("label")
        self.gridLayout_2.addWidget(self.label, 0, 0, 1, 1)
        self.gridLayout.addWidget(self.frame, 1, 0, 1, 1)
        self.frame_3 = QtWidgets.QFrame(self.centralwidget)
        self.frame_3.setMinimumSize(QtCore.QSize(600, 608))
        self.frame_3.setFrameShape(QtWidgets.QFrame.Box)
        self.frame_3.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_3.setObjectName("frame_3")
        self.gridLayout_4 = QtWidgets.QGridLayout(self.frame_3)
        self.gridLayout_4.setObjectName("gridLayout_4")
        # self.graphicsView = QtWidgets.QGraphicsView(self.frame_3)
        # self.graphicsView.setMinimumSize(QtCore.QSize(580, 445))
        # self.graphicsView.setObjectName("graphicsView")
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(self.frame_3)
        self.canvas.setMinimumSize(QtCore.QSize(570, 435))
        self.canvas.setSizePolicy(
            QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding,
                                  QtWidgets.QSizePolicy.MinimumExpanding))
        self.gridLayout_4.addWidget(self.canvas, 1, 0, 1, 1)
        self.toolbar = NavigationToolbar(self.canvas, self.canvas)
        # self.frame_5 = QtWidgets.QFrame(self.frame_3)
        # self.frame_5.setMinimumSize(QtCore.QSize(0, 94))
        # self.frame_5.setMaximumSize(QtCore.QSize(16777215, 135))
        # self.frame_5.setFrameShape(QtWidgets.QFrame.StyledPanel)
        # self.frame_5.setFrameShadow(QtWidgets.QFrame.Raised)
        # self.frame_5.setObjectName("frame_5")
        # self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.frame_5)
        # self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        # self.scrollArea_3 = QtWidgets.QScrollArea(self.frame_5)
        # self.scrollArea_3.setWidgetResizable(True)
        # self.scrollArea_3.setObjectName("scrollArea_3")
        # self.scrollAreaWidgetContents_3 = QtWidgets.QWidget()
        # self.scrollAreaWidgetContents_3.setGeometry(QtCore.QRect(0, 0, 558, 113))
        # self.scrollAreaWidgetContents_3.setObjectName("scrollAreaWidgetContents_3")
        # self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents_3)
        # self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        # self.tableWidget = QtWidgets.QTableWidget(self.scrollAreaWidgetContents_3)
        # self.tableWidget.setMinimumSize(QtCore.QSize(0, 65))
        # self.tableWidget.setObjectName("tableWidget")
        # self.tableWidget.setColumnCount(0)
        # self.tableWidget.setRowCount(0)
        # self.horizontalLayout_3.addWidget(self.tableWidget)
        # self.scrollArea_3.setWidget(self.scrollAreaWidgetContents_3)
        # self.horizontalLayout_2.addWidget(self.scrollArea_3)
        # self.gridLayout_4.addWidget(self.frame_5, 4, 0, 1, 1)
        # self.label_3 = QtWidgets.QLabel(self.frame_3)
        # self.label_3.setObjectName("label_3")
        # self.gridLayout_4.addWidget(self.label_3, 2, 0, 1, 1)
        self.gridLayout.addWidget(self.frame_3, 1, 1, 2, 1)
        self.frame_4 = QtWidgets.QFrame(self.centralwidget)
        self.frame_4.setMinimumSize(QtCore.QSize(800, 32))
        self.frame_4.setMaximumSize(QtCore.QSize(16777215, 32))
        self.frame_4.setFrameShape(QtWidgets.QFrame.Box)
        self.frame_4.setFrameShadow(QtWidgets.QFrame.Raised)
        self.frame_4.setObjectName("frame_4")
        self.horizontalLayoutWidget = QtWidgets.QWidget(self.frame_4)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(10, 0, 111, 31))
        self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(
            self.horizontalLayoutWidget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.openButton = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        self.openButton.setText("")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(":/res/res/open2.ico"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.openButton.setIcon(icon1)
        self.openButton.setObjectName("openButton")
        self.horizontalLayout.addWidget(self.openButton)
        self.saveButton = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        self.saveButton.setText("")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap(":/res/res/save.ico"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.saveButton.setIcon(icon2)
        self.saveButton.setObjectName("saveButton")
        self.horizontalLayout.addWidget(self.saveButton)
        self.saveasButton = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        self.saveasButton.setText("")
        icon3 = QtGui.QIcon()
        icon3.addPixmap(QtGui.QPixmap(":/res/res/saveas.ico"),
                        QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.saveasButton.setIcon(icon3)
        self.saveasButton.setObjectName("saveasButton")
        self.horizontalLayout.addWidget(self.saveasButton)
        self.gridLayout.addWidget(self.frame_4, 0, 0, 1, 2)
        MainWindow.setCentralWidget(self.centralwidget)
        # self.graphicsView = QtWidgets.QGraphicsView(self.frame_3)
        # self.graphicsView.setMinimumSize(QtCore.QSize(580, 445))
        # self.graphicsView.setObjectName("graphicsView")
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 824, 21))
        self.menubar.setObjectName("menubar")
        self.menuProject = QtWidgets.QMenu(self.menubar)
        self.menuProject.setObjectName("menuProject")
        self.menuEdit = QtWidgets.QMenu(self.menubar)
        self.menuEdit.setObjectName("menuEdit")
        self.menuPatrolling = QtWidgets.QMenu(self.menubar)
        self.menuPatrolling.setObjectName("menuPatrolling")
        self.menuSettings = QtWidgets.QMenu(self.menubar)
        self.menuSettings.setObjectName("menuSettings")
        self.menuHelp = QtWidgets.QMenu(self.menubar)
        self.menuHelp.setObjectName("menuHelp")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.menubar.addAction(self.menuProject.menuAction())
        self.menubar.addAction(self.menuEdit.menuAction())
        self.menubar.addAction(self.menuPatrolling.menuAction())
        self.menubar.addAction(self.menuSettings.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())
        self.menuCreatePath = QtWidgets.QAction(MainWindow)
        self.menuCreatePath.setObjectName("menuCreatePath")
        self.menuSplit = QtWidgets.QAction(MainWindow)
        self.menuSplit.setObjectName("menuSplit")
        self.menuPatrolling.addAction(self.menuSplit)
        self.menuPatrolling.addAction(self.menuCreatePath)
        self.retranslateUi(MainWindow)
        # self.label.setDragEnabled(True)
        # self.label_2.setDragEnabled(True)
        # self.label_3.setDragEnabled(True)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "PatrolGIS"))
        self.label_2.setText(_translate("MainWindow", "Layers"))
        self.label.setText(_translate("MainWindow", "Explorer"))
        self.menuProject.setTitle(_translate("MainWindow", "Project"))
        self.menuEdit.setTitle(_translate("MainWindow", "Edit"))
        self.menuPatrolling.setTitle(_translate("MainWindow", "Patrolling"))
        self.menuSettings.setTitle(_translate("MainWindow", "Settings"))
        self.menuHelp.setTitle(_translate("MainWindow", "Help"))
        self.menuCreatePath.setText(_translate("MainWindow", "Generate Path"))
        self.menuSplit.setText(_translate("MainWindow", "Start Processing"))