def dropMimeData(self, mime: QMimeData, action, row: int, column: int, parent: QModelIndex): LOG.debug('dropMimeData at row {}'.format(row)) if action == Qt.IgnoreAction: return True if mime.hasFormat('text/uri-list'): if mime.hasUrls(): LOG.debug('found urls in drop!') paths = [ qurl.path() for qurl in mime.urls() if qurl.isLocalFile() ] self.doc.import_files(paths) # FIXME: replace with a signal return True elif mime.hasFormat(self._mimetype): # unpickle the presentation information and re-insert it # b = base64.decodebytes(mime.text()) b = mime.data(self._mimetype) layer_set_len, insertion_info = pkl.loads(b) LOG.debug('dropped: {0!r:s}'.format(insertion_info)) count = len(insertion_info) if row == -1: row = len(self.doc) # append # FIXME: row=col=-1 implies drop-on-parent # which may mean replace or may mean append for composite layers # self.insertRows(row, count) # for i, presentation in enumerate(l): # self.setData(self.index(row+i, 0), presentation) order = list(range(layer_set_len)) inserted_row_numbers = [] # inserted_presentations = [] # delete_these_rows = [] insertion_point = row uuids = [] for old_row, presentation in reversed(sorted(insertion_info)): del order[old_row] if old_row < insertion_point: insertion_point -= 1 inserted_row_numbers.insert(0, old_row) uuids.append(presentation.uuid) # delete_these_rows.append(old_row if old_row<row else old_row+count) # inserted_presentations.append(presentation) order = order[:insertion_point] + inserted_row_numbers + order[ insertion_point:] LOG.debug('new order after drop {0!r:s}'.format(order)) self.select([]) self.doc.reorder_by_indices(order) # self.doc.insert_layer_prez(row, inserted_presentations) # LOG.debug('after insertion removing rows {0!r:s}'.format(delete_these_rows)) # for exrow in delete_these_rows: # self.doc.remove_layer_prez(exrow) # self.doc.didReorderLayers.emit(order) # FUTURE: not our business to be emitting on behalf of the document assert (count == len(insertion_info)) return True return False
def insertFromMimeData(self, source: QMimeData, disable_richtext: bool = False): ''' ..todo: Add support for embedded content when inserting html mime from clipboard ''' if source.hasImage(): temporary_file = os.path.join( Environment.get_base_path(), Configuration().get_setting( 'oxnote', 'application.directories.temporary', default='.oxnote/tmp'), '{}.png'.format( (str(uuid.uuid4())))) source.imageData().save(temporary_file) with open(temporary_file, 'rb') as f: encoded = base64.b64encode(f.read()) self.textCursor().insertImage('data:image/png;base64,{}'.format( encoded.decode("utf-8"))) if os.path.isfile(temporary_file): os.remove(temporary_file) elif source.hasUrls(): for url in source.urls(): if pathlib.Path(url.fileName()).suffix.lower( )[1:] not in self.supported_image_formats: super().insertFromMimeData(source) continue file_extension = pathlib.Path( url.fileName()).suffix.lower()[1:] if url.isLocalFile(): if not os.path.isfile(url.toLocalFile()): continue with open(url.toLocalFile(), 'rb') as f: self.textCursor().insertImage( 'data:image/png;base64,{}'.format( base64.b64encode(f.read()).decode("utf-8"))) else: response = requests.get(url.toString(), stream=True) if response.status_code == 200: self.textCursor().insertImage( 'data:image/{};base64,{}'.format( file_extension, base64.b64encode( response.content).decode("utf-8"))) elif source.hasHtml() and disable_richtext: self.textCursor().insertText(source.text()) else: super().insertFromMimeData(source)
def dropMimeData(self, mime_data: QtCore.QMimeData, drop_actions: QtCore.Qt.DropActions, row: int, column: int, index: QtCore.QModelIndex) -> bool: urls = mime_data.urls() for url in urls: print(url) print(url.path()) # self.file_uploading.emit(url.path()[1:], self.item(index).file_path) return True
def dropMimeData(self, mime_data: QtCore.QMimeData, drop_actions: QtCore.Qt.DropActions, row: int, column: int, index: QtCore.QModelIndex) -> bool: urls = mime_data.urls() for url in urls: print(url) print(url.path()) # self.file_uploading.emit(url.path()[1:], self.item(index).file_path) return True
def getFilePaths(self): """ Retrieves file paths (from file system, not internal file paths). Return: List """ filePaths = [] if self.hasUrls(): urls = QMimeData.urls() for url in urls: filePaths.append(url.toLocalFile()) return filePaths
def dropMimeData(self, mime_data: QtCore.QMimeData, drop_actions: QtCore.Qt.DropActions, row: int, column: int, index: QtCore.QModelIndex): if not index.isValid() or not drop_actions & QtCore.Qt.CopyAction: return False urls = mime_data.urls() root = mime_data.property('root') print(root) for url in urls: source_path = os.path.dirname(url.path()) filename = os.path.basename(url.path()) print(source_path) print(filename) target_path = self.filePath(index) print(target_path) if root != '': target_path += source_path[source_path.index(root):] print(target_path) self.file_downloading.emit(source_path, target_path, filename) return True
def show_menu(self, clickPos): index = self.tree.indexAt(clickPos) selected_path = self.tree.model().filePath(index) enclosing_dir = self.find_enclosing_dir(selected_path) menu = QMenu(self) openAction = menu.addAction("Open") newFolderAction = menu.addAction("New Folder") newFileAction = menu.addAction("New File") copyAction = menu.addAction("Copy") pasteAction = menu.addAction("Paste") renameAction = menu.addAction("Rename") fileInfo = menu.addAction("Properties") menuPos = QPoint(clickPos.x() + 15, clickPos.y() + 15) action = menu.exec_(self.mapToGlobal(menuPos)) if action == openAction: self.open_file(index) elif action == newFolderAction: path = self.get_dialog_str("New Folder", "Enter name for new folder:") if path: self.mkdir(os.path.join(enclosing_dir, path)) elif action == newFileAction: path = self.get_dialog_str("New File", "Enter name for new file:") if path: self.touch(os.path.join(enclosing_dir, path)) elif action == renameAction: path = self.get_dialog_str("Rename File", "Enter new name:") # Naive validation if "/" in path: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText("Filename cannot contain '/'") msg.setWindowTitle("Error") msg.exec_() return new_path = os.path.join(enclosing_dir, path) self.move(selected_path, new_path) elif action == copyAction: mime_data = QMimeData() # TODO: support multiple selections mime_data.setUrls([QUrl(Path(selected_path).as_uri())]) self.clipboard.setMimeData(mime_data) elif action == pasteAction: mime_data = self.clipboard.mimeData() if not mime_data: return if mime_data.hasUrls(): for src_url in mime_data.urls(): self.copy(src_url.path(), enclosing_dir)
def tablewidget_right_menu(self,pos,file_path=None): item_row = self.tablewidget.currentRow() file_name = self.tablewidget.item(item_row,0).text() file_path = self.tablewidget.item(item_row,4).text() if not file_path: file_path = os.path.join(self.paths[-1],file_name) file_path = file_path.replace('\\','/') # print(file_path) menu = QMenu(self.tablewidget) delete = menu.addAction('删除') copy = menu.addAction('复制') paste = menu.addAction('粘贴') openLocalFile = menu.addAction('浏览本地文件') file_roperty = menu.addAction("属性") action = menu.exec_(self.tablewidget.mapToGlobal(pos)) if action == delete: reply = QMessageBox.warning(self.mainwindow, '删除确认', '确认删除吗?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if os.path.isdir(file_path) and reply == 16384: # print('delete dir') shutil.rmtree(file_path) self.statusBar.showMessage(f'删除 {file_path} 成功!') self.updateFileTree() elif not os.path.isdir(file_path) and reply == 16384: # print('delete file') os.remove(file_path) self.statusBar.showMessage("删除 -> %s 成功!" % file_path) # print(self.paths) self.updateFileTree() self.statusBar.showMessage(f'删除 {file_path} 成功!') elif action == copy: try: data = QMimeData() url = QUrl.fromLocalFile(file_path) clipboard = QApplication.clipboard() data.setUrls([url]) clipboard.setMimeData(data) self.statusBar.showMessage("已复制 -> %s 到剪切板" % file_path) except Exception as e: QMessageBox.about(self.mainwindow, '错误', '文件不存在!') self.statusBar.showMessage("复制 -> %s 出错,文件不存在!" % file_path) elif action == paste: data = QApplication.clipboard().mimeData() source_file_url = data.urls()[0].url() self.paste_thread = FilePasteThread(source_file_url[8:], file_path) self.paste_thread.sinOut.connect(self.filePasteComplete) self.paste_thread.start() elif action == openLocalFile: try: local_path = file_path.replace('/', '\\') os.system("explorer.exe %s" % os.path.dirname(local_path)) except Exception as e: QMessageBox.warning(self.mainwindow, '错误', '打开文件不存在!') elif action == file_roperty: # print('查看文件属性') if os.path.isdir(file_path): file_type = '文件夹' file_image = '../images/folder_status.png' _dir = True else: _dir = False if file_path.endswith('.jpg'): file_type = 'JPG图片文件( *.jpg )' file_image = '../images/jpg_status.png' elif file_path.endswith('.html'): file_type = 'HTML页面文件( *.html )' file_image = '../images/html_status.png' elif file_path.endswith('.xlsx'): file_type = 'XLSX表格文件( *.xlsx )' file_image = '../images/excel_status.png' elif file_path.endswith('.png'): file_type = 'PNG表格文件( *.png )' file_image = '../images/png_status.png' else: file_type = 'Other其他文件类型( *.%s)' % (os.path.splitext(file_path)[1]) file_image = '../images/file_status.png' if _dir: '''文件夹大小去要遍历每个子文件夹与文件累加''' file_size = self.getdirsize(file_path) # print(file_path) statinfo = os.stat(file_path) else: statinfo = os.stat(file_path) file_size = statinfo.st_size file_atime = self.time_format(statinfo.st_atime) # 文件最后访问时间 file_ctime = self.time_format(statinfo.st_ctime) # 文件创建时间 file_mtime = self.time_format(statinfo.st_mtime) # 文件最后修改时间 self.file_status_window = FileStatusWindow() self.file_status_window.filename = file_path.replace('\\', '/').split('/')[-1] self.status_main_window = QMainWindow(MainWindow) self.file_status_window.setupUi(self.status_main_window) self.file_status_window.lineEdit.setText(self.file_status_window.filename) self.file_status_window.label_3.setText(file_type) self.file_status_window.label_5.setText(file_path.replace('/', '\\')) self.file_status_window.label_9.setText(file_ctime) self.file_status_window.label_11.setText(file_mtime) self.file_status_window.label_13.setText(file_atime) self.file_status_window.label_7.setText(self.approximateSize(file_size)) self.file_status_window.pushButton.clicked.connect(self.fileStatusUse) # 应用按钮click出发函数 self.file_status_window.pushButton_2.clicked.connect(self.fileStatusConfirm) self.file_status_window.pushButton_3.clicked.connect(self.fileStatusCancel) pix = QPixmap(file_image) self.file_status_window.label.setPixmap(pix) self.status_main_window.show()