def startDrag(self, event: QEvent) -> None: item = self.currentItem() if item is None: event.ignore() return self.item_being_dragged = self.takeItem(self.row(item)).parent hot_spot_point = event.pos() item_data = QByteArray() data_stream = QDataStream(item_data, QIODevice.WriteOnly) data_stream << hot_spot_point # pixmap << location mime_data = QMimeData() mime_data.setData(config_controller.component_mime, item_data) drag = QDrag(self) pixmap = item.parent.pixmap.scaledToWidth(64) drag.setHotSpot(QPoint(pixmap.width() / 2, pixmap.height() / 2)) drag.setPixmap(pixmap) drag.setMimeData(mime_data) result = drag.start(QtCore.Qt.MoveAction) if result: # == QtCore.Qt.MoveAction: pass
def hCopy(self): """ # slot for action copy_to_clipboard """ sel = self.listWdg.selectedItems() #################### # test code l = [] for item in sel: # get url from path l.append(QUrl.fromLocalFile(item.data(Qt.UserRole)[0])) # init clipboard data q = QMimeData() # set some Windows magic values for copying files from system clipboard : Don't modify # 1 : copy; 2 : move q.setData("Preferred DropEffect", QByteArray(1, "2")) q.setUrls(l) # end of test code ##################### # copy image to clipboard item = sel[0] filename = item.data(Qt.UserRole)[0] if filename.endswith(IMAGE_FILE_EXTENSIONS): q.setImageData(QImage(sel[0].data(Qt.UserRole)[0])) QApplication.clipboard().clear() QApplication.clipboard().setMimeData(q)
def startDrag(self, event): item = self.itemAt(event.scenePos(), self.page_view_transform) if item is None: event.ignore() return self.item_being_dragged = item.parent self.remove_component_controller(item.parent) hotspot = event.scenePos() - item.scenePos() hot_spot_point = hotspot.toPoint() hot_spot_point = self.page_view_transform.map(hot_spot_point) item_data = QByteArray() data_stream = QDataStream(item_data, QIODevice.WriteOnly) data_stream << hot_spot_point # pixmap << location mime_data = QMimeData() mime_data.setData(config_controller.component_mime, item_data) drag = QDrag(self) drag.setMimeData(mime_data) horizontal_scaling = self.page_view_transform.m11() logger.info(f"sceneBoundingRect {item.sceneBoundingRect().width()}") logger.info( f"sceneBoundingRect {item.sceneBoundingRect().width()*horizontal_scaling}" ) drag.setPixmap( item.parent.pixmap.scaledToWidth(item.sceneBoundingRect().width() * horizontal_scaling)) drag.setHotSpot(hot_spot_point) result = drag.start(QtCore.Qt.MoveAction) if result: # == QtCore.Qt.MoveAction: pass
def mimeData(self, indexes): mime_data = QMimeData() element_index = indexes[0].row( ) * ELEMENT_COLUMN_NUMBER + indexes[0].column() # send name of process core to QGraphicsScene data_array = QByteArray(bytes(self._model[element_index].name, 'UTF-8')) mime_data.setData(MimeType.PROCESS_CORE.value, data_array) return mime_data
def mousePressEvent(self, event): if event.button() == Qt.LeftButton: drag = QDrag(self) mime_data = QMimeData() data_text = self.get_drag_data() data = QByteArray(bytes(data_text, 'utf-8')) mime_data.setData('text/plain', data) drag.setMimeData(mime_data) drop_action = drag.exec_() return
def _handle_mouse_press_event_for_dispos(self, ev: QMouseEvent): if ev.button() != QtCore.Qt.LeftButton: return if self.spawns: self.spawn_selected.emit(self) mime_data = QMimeData() mime_data.setData("application/fe14-spawn", b"") drag = QDrag(self) drag.setMimeData(mime_data) drag.setHotSpot(ev.pos()) drag.exec_(QtCore.Qt.MoveAction)
def mimeData(self, indices): logger.debug("mimeData") if len(indices) == 1 and indices[0].isValid(): index = indices[0] item = index.internalPointer().content if isinstance(item, self.SubConfigContent) and isinstance( item.subConfig, CompositeFilter): res = QMimeData() res.setData(self.mimeTypes()[0], item.subConfig.getName().encode("utf8")) return res return None
def mimeData(self, indexes): file_ = self._table.database.file ids = [self._ids[r] for r in list({i.row() for i in indexes})] records = [self._table.GetRow(i) for i in ids] texkeys = [r["texkey"] for r in records if r["texkey"] is not None] data_list = [file_, ids, records] data = QMimeData() data.setData(self.mimeTypes()[0], QByteArray(json.dumps(data_list).encode("utf-8"))) data.setText(", ".join(texkeys)) return data
def startDrag(self, dropActions): item = self.currentItem() # icon = item.icon() data = QByteArray() stream = QDataStream(data, QIODevice.WriteOnly) stream.writeQString(item.text()) stream.writeInt16(item.data(1)) # stream << icon mimeData = QMimeData() mimeData.setData("application/x-lista-item", data) drag = QDrag(self) drag.setMimeData(mimeData) if drag.exec_(Qt.MoveAction) == Qt.MoveAction: self.takeItem(self.row(item))
def mouseMoveEvent(self, event: QGraphicsSceneMouseEvent): if (QLineF(event.screenPos(), event.buttonDownScreenPos( Qt.LeftButton)).length() < QApplication.startDragDistance()): return self.parentItem().edgeDragStart() package = QMimeData() package.setData(self.DragMimeType, bytes()) drag = QDrag(event.widget()) drag.setMimeData(package) drag.exec_() self.parentItem().edgeDragStop()
def mimeData(self, indexes: List[QModelIndex]) -> QMimeData: indexes = [item for item in indexes if item.column() == 0] if not indexes: return None data = typing.cast(_InternalData, indexes[0].internalPointer()) out = QMimeData() out_data = { "id": data["id"], "parent": "", "type": "dir" if "data" not in data else "app", } if data["parent"]: out_data["parent"] = data["parent"].internalPointer()["id"] out.setData(MIMETYPE, json.dumps(out_data).encode("ascii")) return out
def startDrag(self): data = QByteArray() stream = QDataStream(data, QIODevice.WriteOnly) stream.writeQString(self._player_name) stream.writeInt16(self._player_id) mimedata = QMimeData() mimedata.setData("application/x-lista-item", data) drag = QDrag(self) drag.setMimeData(mimedata) if drag.exec_(Qt.MoveAction) == Qt.MoveAction: self._player_name = "" self._player_id = 0 for i in range(self.sorok_szama): self.parent.eredmenyek[self._csoport_number][ self._csoport_sor][i]._set_p1_id(0) self.parent.eredmenyek[self._csoport_number][i][ self._csoport_sor]._set_p2_id(0) self.update()
def mousePressEvent(self, event): label = self.childAt(event.pos()) if not label: return hot_spot = event.pos() - label.pos() mime_data = QMimeData() mime_data.setText(label.text()) mime_data.setData("application/x-hotspot", str(hot_spot.x())) pixmap = QPixmap(label.size()) label.render(pixmap) drag = QDrag(self) drag.setMimeData(mime_data) drag.setPixmap(pixmap) drag.setHotSpot(hot_spot) dropAction = drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction) if dropAction == Qt.MoveAction: label.close()
def _copy(self, cut): """ Copys the selection to clipboard. :param cut: boolean whether the copy is actually a cut. :return: """ logger.internal("Copying...") sc = self.scene() assert isinstance(sc, GraphScene) items = sc.selectedItems() nodes = set() for i in items: if isinstance(i, BaseGraphScene.NodeItem): nodes.add(i.name) saved = sc.graph.getSubConfig().save() if "_guiState" in saved: del saved["_guiState"] toDelIdx = [] deletedNodes = set() for i, n in enumerate(saved["nodes"]): if not n["name"] in nodes: toDelIdx.append(i) deletedNodes.add(n["name"]) for i in toDelIdx[::-1]: saved["nodes"] = saved["nodes"][:i] + saved["nodes"][i + 1:] cToDel = set() for c in saved["connections"]: node1, _, node2, _ = SubConfiguration.connectionStringToTuple(c) if node1 in deletedNodes or node2 in deletedNodes: cToDel.add(c) for c in cToDel: saved["connections"].remove(c) md = QMimeData() md.setData("nexxT/json", json.dumps(saved, indent=2, ensure_ascii=False).encode()) QGuiApplication.clipboard().setMimeData(md) if cut: for n in saved["nodes"]: sc.graph.deleteNode(n["name"]) logger.info("Copyied %d nodes and %d connections", len(saved["nodes"]), len(saved["connections"]))
def mousePressEvent(self, event): hotSpot = event.pos() mimeData = QMimeData() mimeData.setText(self.text()) mimeData.setData('application/x-hotspot', '%d %d' % (hotSpot.x(), hotSpot.y())) pixmap = QPixmap(self.size()) self.render(pixmap) drag = QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(pixmap) drag.setHotSpot(hotSpot) dropAction = drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction) if dropAction == Qt.MoveAction: self.close() self.update()
def mousePressEvent(self, event): hotSpot = event.pos() mimeData = QMimeData() mimeData.setText(self.text()) mimeData.setData('application/x-hotspot', b'%d %d' % (hotSpot.x(), hotSpot.y())) pixmap = QPixmap(self.size()) self.render(pixmap) drag = QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(pixmap) drag.setHotSpot(hotSpot) dropAction = drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction) if dropAction == Qt.MoveAction: self.close() self.update()
def mimeData(self, indexes: List["QModelIndex"]) -> "QMimeData": """ Returns a serialized object representing a List of Keras Layer. Used for drag/drop operations, for example. """ mime_data = QMimeData() # Serializer encoded_data = QByteArray() stream = QDataStream(encoded_data, QIODevice.WriteOnly) # Write all the layers corresponding to the indexes for index in indexes: if index.isValid(): layer = index.internalPointer().layer stream.writeQVariant(layer) # Store the serialized data on the MIME data mime_data.setData(Dial.KerasLayerListMIME.value, encoded_data) return mime_data
def mimeData(self, indexes): """ Returns an object that contains serialized items of data corresponding to the list of indexes specified. """ mimeData = QMimeData() encodedData = QByteArray() stream = QDataStream(encodedData, QIODevice.WriteOnly) for index in indexes: if index.isValid() and index.column() == 0: # Note: We select full rows, but only want to make one item per row item = self.nodeFromIndex(index) # For performance reasons we do not make a full copy # Instead we just serialize unique name and current row # We also don't remove the item using self.removeRows but rather handle it inside of dropMimeData stream.writeInt32(item.typeId()) stream.writeInt64(item.uuid()) stream.writeInt32(index.row()) mimeData.setData("application/vnd.text.list", encodedData) return mimeData
def mouseMoveEvent(self, event): if not (event.buttons() & Qt.LeftButton): return super(ObjectIcon, self).mouseMoveEvent(event) drag = QDrag(self) mime_data = QMimeData() object_bytes = bytearray() if isinstance(self.object, LevelObject): object_bytes.append(0) else: object_bytes.append(1) object_bytes.extend(self.object.to_bytes()) mime_data.setData("application/level-object", object_bytes) drag.setMimeData(mime_data) if drag.exec_() == Qt.MoveAction: self.object_placed.emit()
class SnapWindow(QMainWindow): def __init__(self, app, flags): self.flag_snapped = False # Picture snapped or loaded at start. self.flag_frame = True # Window frame toggling. self.app = app self.winsize = None # None-Conditional toggle on resize. # Also the size the window should be. QMainWindow.__init__(self) self.dragicon = QIcon.fromTheme("folder-new").pixmap(QSize(24,24)) self.imgdata = None self.setWindowTitle("Snap") self.cliplabel = QtWidgets.QLabel(self) self.cliplabel.show() self.cliplabel.setScaledContents(True) self.clip_pix = self.cliplabel.pixmap() self.clipboard = app.clipboard() self.clipboard.dataChanged.connect(self.clipboardChanged) self.clipboard.clear(mode=self.clipboard.Clipboard) p = self.palette() p.setColor(self.backgroundRole(), QtCore.Qt.white) self.setPalette(p) self.hide() def load_from_image(self): self.flag_snapped = True im = QtGui.QImage() im.load(shared['inputfp']) pm = QtGui.QPixmap().fromImage(im) self.original_snap = pm.copy() self.original_size = pm.width(), pm.height() mpos = shared['curpos'] self.setGeometry(mpos.x(),mpos.y(), pm.width(), pm.height()) self.cliplabel.resize(pm.width(),pm.height()) self.cliplabel.setPixmap(pm) self.show() def clipboardChanged(self): if self.flag_snapped == False: self.clipboard = self.app.clipboard() pm = self.clipboard.pixmap() self.original_snap = pm.copy() self.original_size = pm.width(), pm.height() if pm.isNull(): pass else: self.flag_snapped = True mpos = shared['curpos'] self.setGeometry(mpos.x()-pm.width(),mpos.y()-pm.height(), pm.width(), pm.height()) self.cliplabel.resize(pm.width(),pm.height()) self.cliplabel.setPixmap(pm) self.show() def resizeEvent(self, event): super(SnapWindow, self).resizeEvent(event) if self.winsize: self.cliplabel.resize(self.savesize.width(),self.savesize.height()) self.resize(self.savesize.width(),self.savesize.height()) self.winsize = None else: self.cliplabel.resize(self.width(),self.height()) def scale_ratio(self): winsize = QSize(self.width(),self.height()) new_size = QSize(self.original_size[0],self.original_size[1]) new_size.scale(winsize, QtCore.Qt.KeepAspectRatio) self.cliplabel.resize(new_size) self.resize(new_size) def reset_size(self): origsize = QSize(self.original_size[0],self.original_size[1]) self.cliplabel.resize(origsize) self.cliplabel.setPixmap(self.original_snap) self.resize(origsize) def mousePressEvent(self, event): super(SnapWindow, self).mousePressEvent(event) if event.button() == QtCore.Qt.MouseButton.LeftButton: self.scale_ratio() self.QDrag = QDrag(self) self.QMimeData = QMimeData() self.imgdata = QByteArray() imgbuffer = QBuffer(self.imgdata) imgbuffer.open(QIODevice.WriteOnly) self.original_snap.save(imgbuffer, "PNG") self.QMimeData.setImageData(self.imgdata) self.QMimeData.setData("image/png", self.imgdata) self.QDrag.setMimeData(self.QMimeData) self.QDrag.setPixmap(self.dragicon) dropaction = self.QDrag.exec_(Qt.CopyAction) def contextMenuEvent(self, event): menu = QtWidgets.QMenu(self) action_rename = menu.addAction("Rename") action_clipboard = menu.addAction("Copy to Clipboard (Again)") action_save = menu.addAction("Save Original") action_reset = menu.addAction("Reset to Original") action_frame = menu.addAction("Toggle Frame") action_close = menu.addAction("Close") action = menu.exec_(self.mapToGlobal(event.pos())) if action == action_save: self.save_copy() elif action == action_clipboard: self.clipboard.setPixmap(self.original_snap) elif action == action_reset: self.reset_size() elif action == action_frame: if self.flag_frame == True: self.flag_frame = False self.setWindowFlag(QtCore.Qt.FramelessWindowHint, True) self.hide() self.show() self.winsize = self.size() else: self.flag_frame = True self.setWindowFlag(QtCore.Qt.FramelessWindowHint, False) self.hide() self.show() self.winsize = self.size() self.reset_size() elif action == action_close: self.close() elif action == action_rename: name, tmp = QInputDialog.getText(self, "", "Name this window:") self.setWindowTitle(name) def save_copy(self): fd = QtWidgets.QFileDialog() fd.setDirectory(QtCore.QDir('~/')) savefn = fd.getSaveFileName(self, 'Save File')[0] pixmap = self.original_snap barray = QtCore.QByteArray() qbuffer = QtCore.QBuffer(barray) qbuffer.open(QtCore.QIODevice.WriteOnly) pixmap.save(qbuffer, "PNG") bytesio = BytesIO(barray.data()) bytesio.seek(0) with open(savefn, 'wb') as savefile: savefile.write(bytesio.read())