def dropEvent(self, event: QtGui.QDropEvent) -> None: item: QtWidgets.QTreeWidgetItem = self.itemAt(event.pos()) if not item: return event.setDropAction(Qt.IgnoreAction) source = self.preset_for_item(self.currentItem()) target = self.preset_for_item(item) if source is None or target is None: return event.setDropAction(Qt.IgnoreAction) if source.game != target.game or source.base_preset_uuid is None: return event.setDropAction(Qt.IgnoreAction) try: source_preset = source.get_preset() except InvalidPreset: return event.setDropAction(Qt.IgnoreAction) self.window_manager.preset_manager.add_new_preset( VersionedPreset.with_preset( dataclasses.replace(source_preset, base_preset_uuid=target.uuid))) return super().dropEvent(event)
def dropEvent(self, event: QDropEvent) -> None: """ If the user drops an activity into the activity parameters table read the relevant data from the database and generate a new row. Also, create a warning if the activity is from a read-only database """ db_table = event.source() if project_settings.settings["read-only-databases"].get( db_table.database_name, True): simple_warning_box( self, "Not allowed", "Cannot set activity parameters on read-only databases") return keys = [db_table.get_key(i) for i in db_table.selectedIndexes()] event.accept() # Block signals from `signals` while iterating through dropped keys. signals.blockSignals(True) for key in keys: act = bw.get_activity(key) if act.get("type", "process") != "process": simple_warning_box( self, "Not allowed", "Activity must be 'process' type, '{}' is type '{}'.". format(act.get("name"), act.get("type"))) continue self.add_parameter(key) signals.blockSignals(False) signals.parameters_changed.emit()
def dropEvent(self, event: QDropEvent): if not event.isAccepted() and event.source() == self: drop_row = self.drop_on(event) rows = sorted(set(item.row() for item in self.selectedItems())) rows_to_move = [[ QTableWidgetItem(self.item(row_index, column_index)) for column_index in range(self.columnCount()) ] for row_index in rows] for row_index in reversed(rows): self.removeRow(row_index) if row_index < drop_row: drop_row -= 1 for row_index, data in enumerate(rows_to_move): row_index += drop_row self.insertRow(row_index) for column_index, column_data in enumerate(data): self.setItem(row_index, column_index, column_data) event.accept() for row_index in range(len(rows_to_move)): self.item(drop_row + row_index, 0).setSelected(True) self.item(drop_row + row_index, 1).setSelected(True) super().dropEvent(event) self.dropSignal.emit([self.objectName()])
def dropEvent(self, event: QtGui.QDropEvent) -> None: if event.mimeData().hasUrls(): for url in event.mimeData().urls(): self.files.addItem(url.toLocalFile()) event.acceptProposedAction() else: super().dropEvent(event)
def dropEvent(self, event: QDropEvent) -> None: mime_dict = {} for format in event.mimeData().formats(): mime_dict[format] = event.mimeData().data(format) file_path_bytes = mime_dict['application/x-qt-windows-mime;value="FileNameW"'] file_path = file_path_bytes.data().decode().replace('\x00', '') self.selected_file = file_path self.update_selected_file()
def dropEvent(self, event: QtGui.QDropEvent) -> None: if not event.mimeData().hasUrls(): # pragma: no cover return super().dropEvent(event) paths = [Path(url.toLocalFile()) for url in event.mimeData().urls()] event.acceptProposedAction() self.openDocument(paths)
def handle_drop_event(e: QDropEvent, callback): for url in e.mimeData().urls(): if url.isLocalFile(): callback(url.toLocalFile()) e.accept() return e.ignore()
def dropEvent(self, event: QtGui.QDropEvent) -> None: if event.mimeData().hasUrls(): urls = event.mimeData().urls() for url in urls: if url.isLocalFile(): path = Path(url.toLocalFile()) if self.validPath(path): self.addPath(path) event.acceptProposedAction() else: # pragma: no cover super().dropEvent(event)
def dropEvent(self, event: QtGui.QDropEvent): super().dropEvent(event) if event.mimeData().hasFormat("text/uri-list"): pos = QtCore.QRect() pos.setX(int(event.pos().x())) pos.setY(int(event.pos().y())) pos.setWidth(200) # TODO find a better way to set default width db = QtCore.QMimeDatabase() if "image" in db.mimeTypeForUrl(event.mimeData().urls()[0]).name(): image = event.mimeData().urls()[0].url() id = self._next_id("Image") item = PageItem(id, pos, img=image, height_from_width=True) self._add_item(item) elif "application/octet-stream" in db.mimeTypeForUrl( event.mimeData().urls()[0]).name(): # If it's a stream, we need to download it. However, that could be arbitrarily huge # For now, we're going to base the decision on the file extension. url = event.mimeData().urls()[0].url() if url.endswith(".png") or url.endswith( ".jpg") or url.endswith(".jpeg") or url.endswith( ".gif"): id = self._next_id("Image") item = PageItem(id, pos, img=url, height_from_width=True) self._add_item(item) event.accept()
def dropEvent(self, event: QtGui.QDropEvent): item_index = self.indexAt(event.pos()) item = self.model.itemFromIndex(item_index) morpheme_item = self._current_row[0] if isinstance(item, MorphemeItem): parent_index = item_index.parent() parent = self.model.itemFromIndex(parent_index) parent.appendRow(self._current_row) self.model.dictionary.edit(morpheme_item.morpheme.dict_id, 'is_stem', item.morpheme.is_stem) elif isinstance(item, FixedItem): item.appendRow(self._current_row) if item.text() == 'Stems': self.model.dictionary.edit(morpheme_item.morpheme.dict_id, 'is_stem', True) elif item.text() == 'Affixes': self.model.dictionary.edit(morpheme_item.morpheme.dict_id, 'is_stem', True) else: self.model.dictionary.edit(morpheme_item.morpheme.dict_id, 'is_stem', None) else: raise TypeError('{} instead of MorphemeItem ' 'or FixedItem'.format(type(item))) self._current_row = None
def dropEvent(self, event: QtGui.QDropEvent) -> None: urls: List[QtCore.QUrl] = event.mimeData().urls() paths = [ pathlib.Path(x.toLocalFile()) for x in urls if self.mimeDb.mimeTypeForUrl(x).name().startswith('audio/') ] self.loadPlaylistTask.musicFiles = paths self.loadPlaylistTask.start() self.initProgressDialog()
def dropEvent(self, event: QDropEvent): dir_or_path = event.mimeData().text().replace('file://', '').replace( '\r', '').replace('\n', '') fns = [] if os.path.isdir(dir_or_path): if not dir_or_path.endswith('/'): dir_or_path += '/' for f in os.listdir(dir_or_path): fns.append(dir_or_path + f) else: fns.append(dir_or_path) # sorted by the last interger preceding the .tif fns = sorted(fns, key=lambda x: int(re.search('(\d+)\.tif', x).group(1))) if self.vol1.geometry().contains(event.pos()): self.vol1_fns = fns.copy() self.Vol1show(1) # start with 1 not 0 self.refresh_plot_and_label(self.vol1_fns, self.accumulated_value1, self.accum_plot1) elif self.vol2.geometry().contains(event.pos()): self.vol2_fns = fns.copy() self.Vol2show(1) # start with 1 not 0 self.refresh_plot_and_label(self.vol2_fns, self.accumulated_value2, self.accum_plot2) else: # ignore if been dropped at elsewhere pass if self.vol1_fns and self.vol2_fns is not None: if self.vol1_fns.__len__ != self.vol2_fns.__len__: self.log_window(Msg='vol1 and vol2 do not have same shape') # set slider and LCD max_slide = len( self.vol1_fns if self.vol1_fns is not None else self.vol2_fns) self.Slider.setMaximum(max_slide) self.setLED(actual=1, total=max_slide)
def dropEvent(self, e): # Getting the event source button = QDropEvent.source(e) # Calculating the new coordinates new_x = e.pos().x() - button.getCursorX() new_y = e.pos().y() - button.getCursorY() # Moving the button if it is still in frame if new_x > 350 and new_y > 120 and new_x < 1100 and new_y < 640: position = QPoint(new_x, new_y) button.move(position) e.setDropAction(Qt.MoveAction) e.accept()
def dropEvent(self, event: QtGui.QDropEvent): if (event.mimeData().hasUrls()): cursor = None working_path = None for cur_path in event.mimeData().urls(): if (cur_path.isLocalFile()): path = cur_path.path(options=QtCore.QUrl.FullyDecoded) if (isinstance(pathlib.PurePath(), pathlib.PureWindowsPath) and path.startswith("/")): path = path[1:] with open(path, "rb") as f: try: cursor = load_cursor(f) working_path = path except ValueError as e: print(e) else: try: req = urlopen(cur_path.url()) data = BytesIO(req.read()) data.seek(0) cursor = load_cursor(data) working_path = None except (URLError, ValueError) as e: print(e) if (cursor is not None): self.current_cursor = cursor self._current_file = working_path event.acceptProposedAction() return if (event.mimeData().hasImage()): mem_img = BytesIO() buffer = QtCore.QBuffer() image = QtGui.QImage(event.mimeData().imageData()) image.save(buffer, "PNG") mem_img.write(buffer) mem_img.seek(0) self.current_cursor = load_cursor(mem_img) self._current_file = None event.acceptProposedAction() return
def dropEvent(self, event: QtGui.QDropEvent): from randovania.layout.preset_migration import VersionedPreset for url in event.mimeData().urls(): path = Path(url.toLocalFile()) if path.suffix == f".{LayoutDescription.file_extension()}": self.open_game_details(LayoutDescription.from_file(path)) return elif path.suffix == f".{VersionedPreset.file_extension()}": self.main_tab_widget.setCurrentWidget(self.welcome_tab) self.welcome_tab_widget.setCurrentWidget(self.tab_create_seed) self.generate_seed_tab.import_preset_file(path) return
def test_drop_invalid_drag_on_design_view(self): mime_data = QMimeData() gv = self.toolbox.ui.graphicsView pos = QPoint(0, 0) event = QDropEvent(pos, Qt.CopyAction, mime_data, Qt.NoButton, Qt.NoModifier) with mock.patch('PySide2.QtWidgets.QGraphicsSceneDragDropEvent.source' ) as mock_drop_event_source, mock.patch.object( self.toolbox, "project"), mock.patch.object( self.toolbox, "show_add_project_item_form" ) as mock_show_add_project_item_form: mock_drop_event_source.return_value = "Invalid source" gv.dropEvent(event) mock_show_add_project_item_form.assert_not_called() item_shadow = gv.scene().item_shadow self.assertIsNone(item_shadow)
def dropEvent(self, event: QDropEvent): if event.mimeData().hasUrls(): files = self._get_drop_event_files(event.mimeData()) if files: for file in files: self.main_menu.file_menu.guess_open_file(file) event.accept() return True event.ignore() return False
def test_drop_project_item_on_design_view(self): mime_data = QMimeData() item_type = next(iter(self.toolbox.item_factories)) mime_data.setText(f"{item_type},spec") gv = self.toolbox.ui.graphicsView scene_pos = QPointF(44, 20) pos = gv.mapFromScene(scene_pos) event = QDropEvent(pos, Qt.CopyAction, mime_data, Qt.NoButton, Qt.NoModifier) with mock.patch('PySide2.QtWidgets.QGraphicsSceneDragDropEvent.source' ) as mock_drop_event_source, mock.patch.object( self.toolbox, "project"), mock.patch.object( self.toolbox, "show_add_project_item_form" ) as mock_show_add_project_item_form: mock_drop_event_source.return_value = ProjectItemDragMixin() gv.dropEvent(event) mock_show_add_project_item_form.assert_called_once() mock_show_add_project_item_form.assert_called_with(item_type, scene_pos.x(), scene_pos.y(), spec="spec") item_shadow = gv.scene().item_shadow self.assertTrue(item_shadow.isVisible()) self.assertEqual(item_shadow.pos(), scene_pos)
def dropEvent(self, drop_event: QDropEvent): # 6 print('Drag Drop') url: QUrl = None urls = drop_event.mimeData().urls() for url in urls: print(url.toLocalFile())
def dropEvent(self, event: QtGui.QDropEvent) -> None: # pragma: no cover """Accepts tabbar drops.""" if event.mimeData().hasFormat("application/x-pewpewtabbar"): self.tabs.dropEvent(event)
def dropEvent(self, event: QtGui.QDropEvent) -> None: if event.mimeData().hasUrls(): for url in event.mimeData().urls(): self.loadFile(url.toLocalFile()) break event.acceptProposedAction() elif event.mimeData().hasText(): text = event.mimeData().text() data = np.genfromtxt(text.split("\n"), usecols=0, dtype=np.float64) data = data[~np.isnan(data)] if data.size == 0: event.ignore() return self.loadData(data) event.acceptProposedAction() elif event.mimeData().hasHtml(): pass else: super().dropEvent(event)
def dropEvent(self, event: QtGui.QDropEvent) -> None: # pragma: no cover dest = self.tabAt(event.pos()) src, ok = event.mimeData().data("application/x-pew2tabbar").toInt() if ok and event.source() == self: self.moveTab(src, dest) event.acceptProposedAction() elif ok and isinstance(event.source(), ViewTabBar): text = event.source().tabText(src) widget = event.source().view.stack.widget(src) event.source().view.removeTab(src) index = self.view.insertTab(dest, text, widget) self.setCurrentIndex(index) widget.activate() event.acceptProposedAction() else: event.rejectProposedAction()
def dropEvent(self, event: QDropEvent): if not self.terrain_mode and event.mimeData().hasFormat( "application/fe14-spawn"): event.acceptProposedAction() else: event.ignore()
def dropEvent(self, event: QtGui.QDropEvent): if event.mimeData().hasText(): mime = event.mimeData() transectData = json.loads(mime.text()) transect = Transect(transectData["name"], transectData["numPhotos"]) if self.contains(transect): QtWidgets.QMessageBox.warning( self, "ImageWAO", f"Cannot move transect to this person because they already own the transect. {transect}", QtWidgets.QMessageBox.Ok, ) event.ignore() else: dragTransect = self.addTransect(transect) dragTransect.setBackgroundColor( QtGui.QColor(transectData["color"])) self._sortTransects() if event.source() in self.children(): event.setDropAction(QtCore.Qt.MoveAction) else: event.setDropAction(QtCore.Qt.MoveAction) event.accept() self.contentsChanged.emit() else: event.ignore()
def dropEvent(self, a0: QtGui.QDropEvent) -> None: drag_end_row = self.indexAt(a0.pos()).row() self.model().moveRow(QModelIndex(), self.drag_start_row, QModelIndex(), drag_end_row) a0.acceptProposedAction()
def dropEvent(self, event: QDropEvent): uri: QUrl = event.mimeData().urls()[0] self.update_selected_path(uri)
def drop_event(self, e: QDropEvent): mime: QMimeData = e.mimeData() src = e.source() # -- File drop -- if mime.hasUrls(): destination_index = self.view.indexAt(e.pos()) for url in mime.urls(): local_path = Path(url.toLocalFile()) if not path_exists(local_path): continue self.file_drop(local_path, destination_index) e.accept() return # --- Internal View Drops --- if not isinstance(src, self.view.__class__): e.ignore() return e.setDropAction(Qt.MoveAction) if src is not self.view: e.setDropAction(Qt.CopyAction) if e.keyboardModifiers() == Qt.ShiftModifier: e.setDropAction(Qt.CopyAction) # -- Copy drop -- if e.dropAction() is Qt.CopyAction: destination_index = self.view.indexAt(e.pos()) self.copy_drop(src, destination_index) e.accept() # -- Drag move -- if e.dropAction() is Qt.MoveAction: destination_index = self.view.indexAt(e.pos()) self.move_drop(destination_index) # Ignore default view behaviour e.ignore()
def dropEvent(self, event: QDropEvent): mime_data = event.mimeData() url = mime_data.urls()[0] file_name = url.toLocalFile() if file_name.endswith("lua_profile_json.txt"): self.handle_json_file(file_name)
def dropEvent(self, event: QDropEvent) -> None: event.accept() self.setDisabled(True) self.repaint() asyncio.create_task(self.checkInstallFromURLs(event.mimeData().urls()))
def dropEvent(self, event: QDropEvent): mime_data: QMimeData = event.mimeData() for url in mime_data.urls(): file_name = url.toLocalFile() if os.path.splitext(file_name)[1][1:] == "pak": self.ui.file_list_view.addItem(file_name)