def mousePressEvent(self, event): mime = QMimeData() itemData = QByteArray() mime.setData('application/x-dnditemdata', itemData) drag = QDrag(self) drag.setMimeData(mime) drag.exec_(Qt.MoveAction)
def mousePressEvent(self, event): child = self.childAt(event.pos()) if not child: return pixmap = QPixmap(child.pixmap()) itemData = QByteArray() dataStream = QDataStream(itemData, QIODevice.WriteOnly) dataStream << pixmap << QPoint(event.pos() - child.pos()) mimeData = QMimeData() mimeData.setData('application/x-dnditemdata', itemData) drag = QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(pixmap) drag.setHotSpot(event.pos() - child.pos()) tempPixmap = QPixmap(pixmap) painter = QPainter() painter.begin(tempPixmap) painter.fillRect(pixmap.rect(), QColor(127, 127, 127, 127)) painter.end() child.setPixmap(tempPixmap) if drag.exec_(Qt.CopyAction | Qt.MoveAction, Qt.CopyAction) == Qt.MoveAction: child.close() else: child.show() child.setPixmap(pixmap)
def testMove(self): w = self.newWidget() item = w._path_item_map.get("/Variables/u") #b = w.tree.getBlockInfo("/Variables/u") w.scrollToItem(item) point = w.visualItemRect(item).center() item1 = w._path_item_map.get("/Variables/v") #b1 = w.tree.getBlockInfo("/Variables/v") w.scrollToItem(item1) point1 = w.visualItemRect(item1).bottomLeft() #idx = b.parent.children_list.index(b.name) #idx1 = b.parent.children_list.index(b1.name) w.setCurrentItem(item) mime = QMimeData() mime.setData(w._mime_type, "some data") ee = QDragEnterEvent(w.mapToGlobal(point), Qt.MoveAction, mime, Qt.LeftButton, Qt.NoModifier) w.dragEnterEvent(ee) #Testing.process_events(t=1) de = QDropEvent(w.mapToGlobal(point1), Qt.MoveAction, mime, Qt.LeftButton, Qt.NoModifier) w.dropEvent(de) # This doesn't seem to work for some reason #self.assertEqual(idx1, b.parent.children_list.index(b.name)) #self.assertEqual(idx, b.parent.children_list.index(b1.name)) w.setCurrentItem(None) self.assertEqual(w._current_drag, None) w.dropEvent(de) w.dragEnterEvent(ee) self.assertEqual(w._current_drag, None) w.setCurrentItem(item1) w.dragEnterEvent(ee) self.assertNotEqual(w._current_drag, None) w.dropEvent(de)
def mouseMoveEvent(self, event): """ If the mouse moves far enough when the left mouse button is held down, start a drag and drop operation. """ if not event.buttons() & Qt.LeftButton: return if (event.pos() - self.dragStartPosition).manhattanLength() \ < QApplication.startDragDistance(): return if not self.hasImage: return drag = QDrag(self) mimeData = QMimeData() output = QByteArray() outputBuffer = QBuffer(output) outputBuffer.open(QIODevice.WriteOnly) self.imageLabel.pixmap().toImage().save(outputBuffer, 'PNG') outputBuffer.close() mimeData.setData('image/png', output) drag.setMimeData(mimeData) drag.setPixmap(self.imageLabel.pixmap().scaled(64, 64, Qt.KeepAspectRatio)) drag.setHotSpot(QPoint(drag.pixmap().width() / 2, drag.pixmap().height())) drag.start()
def mimeData(self, indexes): """ Public method to return the mime data. @param indexes list of indexes (QModelIndexList) @return mime data (QMimeData) """ from .XbelWriter import XbelWriter data = QByteArray() stream = QDataStream(data, QIODevice.WriteOnly) urls = [] for index in indexes: if index.column() != 0 or not index.isValid(): continue encodedData = QByteArray() buffer = QBuffer(encodedData) buffer.open(QIODevice.ReadWrite) writer = XbelWriter() parentNode = self.node(index) writer.write(buffer, parentNode) stream << encodedData urls.append(index.data(self.UrlRole)) mdata = QMimeData() mdata.setData(self.MIMETYPE, data) mdata.setUrls(urls) return mdata
def copy(self): """Copy to the clipboard""" data = QMimeData() text = '\n'.join([cursor.selectedText() \ for cursor in self.cursors()]) data.setText(text) data.setData(self.MIME_TYPE, text.encode('utf8')) QApplication.clipboard().setMimeData(data)
def mimeData(self, indexes): """See QAbstractItemModel documentation""" if len(indexes) != 1: return 0 data = QMimeData() data.setData(self.mimeTypes()[0], QByteArray.number(indexes[0].row())) return data
def setCustomData(self, type, data): """ Set custom data. Args: type: str data: QByteArray """ QMimeData.setData(self.getMimeFormatForType(type), data)
def mimeData(self, indexes): sortedIndexes = sorted([index for index in indexes if index.isValid()], key=lambda index: index.row()) encodedData = '\n'.join( self.data(index, Qt.DisplayRole) for index in sortedIndexes) mimeData = QMimeData() mimeData.setData(self.Mimetype, encodedData) return mimeData
def mimeData(self, qidxs): paths = [ qidx.data(self.MessageFileRole) for qidx in qidxs if qidx.column() == 0 ] mime = QMimeData() mime.setData('text/x-lierre-messages', json.dumps(paths).encode('ascii')) return mime
def mimeData(self, indices): data = QMimeData() for index in indices: # only select file node node = self.itemFromIndex(index) if isinstance(node, RemoteFileSystemNode): data.setData('seaside/remote-item', bytes(node.path, 'ascii')) # data.setData('text/uri-list', b'sftp://' + bytes(self._conn._server + '/' + node.path, 'ascii')) self._item_from_path[node.path] = node return data
def copyOutlines(self): glyph = self.view.glyph() clipboard = QApplication.clipboard() mimeData = QMimeData() copyGlyph = glyph.getRepresentation("defconQt.FilterSelection") mimeData.setData( "application/x-defconQt-glyph-data", pickle.dumps([copyGlyph.serialize(blacklist=("name", "unicode"))])) clipboard.setMimeData(mimeData)
def mimeData(self, idxs): mimedata = QMimeData() for idx in idxs: if idx.isValid(): txt = self.data(idx, Qt.DisplayRole) txt2 = bytearray() txt2.extend(map(ord, txt)) mimedata.setData("component/name", txt2) return mimedata
def copyFunc(): d = {} for param in self.rois: if param.selected: roiFile = param.roiFile d[(roiFile.name, roiFile.number)] = roiFile.getRoi() mimeData = QMimeData() mimeData.setData('pickleRoi', pickle.dumps(d)) QApplication.clipboard().setMimeData(mimeData)
def mimeData(self, index_list): data = QMimeData() g_list = [] for idx in index_list: g = idx.data(GalleryModel.GALLERY_ROLE) if g != None: g_list.append(g) data.setData("list/gallery", QByteArray(pickle.dumps(g_list))) return data
def mkMimeDez(self, strip): racked, index = self._findStripIndex(lambda s: s is strip) str_data = '%d %d' % (index.row(), index.column()) if racked else str(index) data = QByteArray() data.append(str_data.encode('utf8')) mime = QMimeData() mime.setData(strip_mime_type, data) return mime
def _handle_copy_binary(self): mime = QMimeData() # mime type suggested here: http://stackoverflow.com/a/6783972/87207 try: mime.setData("application/octet-stream", binascii.a2b_hex(self._selected_data)) except TypeError: raise Exception("TOP values are not supported yet") QApplication.clipboard().setMimeData(mime)
def mimeData(self, indexes): mimeData = QMimeData() encodedData = QByteArray() stream = QDataStream(encodedData, QIODevice.WriteOnly) for index in indexes: if (index.isValid()): stream.writeInt(self.tileIndexAt(index)) mimeData.setData(TILES_MIMETYPE, encodedData) return mimeData
def mousePressEvent(self, me): if me.button() == Qt.LeftButton: child = self.find_label() if child != None: mime_data = QMimeData() mime_data.setData('text/plain', child.get_text()) drag = QDrag(self) drag.setMimeData(mime_data) #drag.setHotSpot(child.pos()) drag_action = drag.exec_(Qt.CopyAction | Qt.MoveAction)
def copyOutlines(self): glyph = self.view.glyph() clipboard = QApplication.clipboard() mimeData = QMimeData() copyGlyph = glyph.getRepresentation("defconQt.FilterSelection") mimeData.setData("application/x-defconQt-glyph-data", pickle.dumps([copyGlyph.serialize( blacklist=("name", "unicode") )])) clipboard.setMimeData(mimeData)
def fromSVG(layerNode, svgContent, document=None): """Paste given `svgContent` to `position` in '`layerNode` Given `layerNode` must be a 'vectorlayer' The `position` value can be: - None, in this case, pixmap will be pasted at position (0, 0) - A QPoint() object, pixmap will be pasted at defined position Note: - If document is None, consider that active document contains layer - If document is provided, it must contains layerNode Method return a list of shapes (shape inserted into layer) """ if isinstance(svgContent, str): svgContent=svgContent.encode() if not isinstance(svgContent, bytes): raise EInvalidType("Given `svgContent` must be a valid <str> or <bytes> SVG document") if not isinstance(layerNode, Node) or layerNode.type()!='vectorlayer': raise EInvalidType("Given `layerNode` must be a valid <VectorLayer>") if document is None: document=Krita.instance().activeDocument() if not isinstance(document, Document): raise EInvalidType("Given `layerNode` must be a valid <Document>") shapes=[shape for shape in layerNode.shapes()] activeNode=document.activeNode() document.setActiveNode(layerNode) document.waitForDone() # Note: following sleep() is here because waitForDone() doesn't seems to # wait for active node changed... # set an arbitrary sleep() delay allows to ensure that node is active # at the end of method execution # hope current delay is not too short (works for me... but can't put # a too long delay) # # Problem occurs with krita 4.4.2 & and tested Krita plus/next tested [2020-01-05] EKritaNode.__sleep(100) mimeContent=QMimeData() mimeContent.setData('image/svg', svgContent) mimeContent.setData('BCIGNORE', b'') QGuiApplication.clipboard().setMimeData(mimeContent) Krita.instance().action('edit_paste').trigger() newShapes=[shape for shape in layerNode.shapes() if not shape in shapes] return newShapes
def mimeData(self, indexes): data = QMimeData() widgets = [] for index in indexes: widget = index.data(Qt.UserRole) widgets.append(widget) widgettext = yaml.dump(widgets).encode("utf-8") _bytes = QByteArray(widgettext) data.setData(self.mimeTypes()[0], _bytes) return data
def mimeData(self, indexes): dataList = [] index = indexes[0] for index in indexes: path = self.pathForIndex(index) data = ','.join(map(str, path)) dataList.append(data) data = '|'.join(dataList) mimeData = QMimeData() mimeData.setData(MIME_NODEPATHS, QByteArray(data.encode())) return mimeData
def mimeData(self, indexes) -> 'QMimeData': mimeData = QMimeData() encodedData = QByteArray() stream = QDataStream(encodedData, QIODevice.WriteOnly) rows = set(index.row() for index in indexes) for row in rows: stream.writeInt32(row) mimeData.setData('application/x-tableview-dragRow', encodedData) return mimeData
def _copy_results_current(self, grid): """Copy cell results for the current cell""" current = grid.current data = grid.model.code_array[current] if data is None: return clipboard = QApplication.clipboard() # Get renderer for current cell renderer = grid.model.code_array.cell_attributes[current]["renderer"] if renderer == "text": clipboard.setText(repr(data)) elif renderer == "image": if isinstance(data, BasicQImage): clipboard.setImage(data) else: # We may have an svg image here try: svg_bytes = bytes(data) except TypeError: svg_bytes = bytes(data, encoding='utf-8') if is_svg(svg_bytes): mime_data = QMimeData() mime_data.setData("image/svg+xml", svg_bytes) clipboard.setMimeData(mime_data) elif renderer == "markup": mime_data = QMimeData() mime_data.setHtml(str(data)) # Also copy data as plain text doc = QTextDocument() doc.setHtml(str(data)) mime_data.setText(doc.toPlainText()) clipboard.setMimeData(mime_data) elif renderer == "matplotlib" and isinstance(data, matplotlib_figure.Figure): # We copy and svg to the clipboard svg_filelike = io.BytesIO() png_filelike = io.BytesIO() data.savefig(svg_filelike, format="svg") data.savefig(png_filelike, format="png") svg_bytes = (svg_filelike.getvalue()) png_image = QImage().fromData(png_filelike.getvalue()) mime_data = QMimeData() mime_data.setData("image/svg+xml", svg_bytes) mime_data.setImageData(png_image) clipboard.setMimeData(mime_data)
def mouseMoveEvent(self, event): if event.buttons() != Qt.LeftButton: return mime_data = QMimeData() mime_data.setData('application/pinytoTask', self.task.to_json().encode('utf-8')) mime_data.setText(self.task.text) drag_object = QDrag(self) drag_object.setMimeData(mime_data) drag_object.setHotSpot(event.pos() - self.rect().topLeft()) drag_object.setPixmap(self.grab()) dropAction = drag_object.exec_(Qt.MoveAction)
def mimeData(self, indexes): mimeData = QMimeData() encodedData = QByteArray() stream = QDataStream(encodedData, QIODevice.WriteOnly) for index in indexes: if (index.isValid()): frame = self.mFrames.at(index.row()) stream.writeInt(frame.tileId) stream.writeInt(frame.duration) mimeData.setData(FRAMES_MIMETYPE, encodedData) return mimeData
def _setClipboardTags(tags): """ Save the given list of tags in the clipboard, both as json and binary. """ mime = QMimeData() binaryData = pickle.dumps(tags) mime.setData(_TAGS_MIME_TYPE, binaryData) # This is only to support pasting outside of puddletag jsonData = json.dumps(list(map(tag_to_json, tags))) mime.setText(jsonData) QApplication.clipboard().setMimeData(mime)
def on_verticalLineButton_pressed(self): mime_data = QMimeData() mime_data.setData('application/x-vertical-line', b'vertical line') mime_data.setText(self.verticalLineButton.text()) drag = QDrag(self.verticalLineButton) drag.setMimeData(mime_data) pixmap = QPixmap( pkg_resources.resource_filename('wiggle.app.panosphere.images', 'VerticalLine32.png')) drag.setHotSpot(QPoint(16, 4)) drag.setPixmap(pixmap) drag.exec(Qt.CopyAction)
def mouseMoveEvent(self, event): drag = QDrag(self) # make the drag look like our widget pixmap = self.grab() drag.setPixmap(pixmap) # empty for now mime_data = QMimeData() data = [self.x, self.y] mime_data.setData("application/x-nakki-construction-label", bytes(json.dumps(data), "utf-8")) drag.setMimeData(mime_data) drag.exec()
def copy(self): glyphs = self.glyphCellView.glyphs() pickled = [] for index in sorted(self.glyphCellView.selection()): pickled.append(glyphs[index].serialize( blacklist=("name", "unicode") )) clipboard = QApplication.clipboard() mimeData = QMimeData() mimeData.setData("application/x-trufont-glyph-data", pickle.dumps(pickled)) clipboard.setMimeData(mimeData)
def mouseMoveEvent(self, event): """Implements mouseMoveEvent() method. Executes drag action and gets coordinate of square under mouse.""" # Coordinate help square = self.squareAt(event.pos(), self.orientation[0]) text = chr(square.x() + 97) + str(square.y() + 1) square = self.squareAt(event.pos()) self.coordinate = (square, text) self.update() # Drag action if not event.buttons() == Qt.LeftButton: return if not self.clickedSquare or not self.dragStart: return if (event.pos() - self.dragStart).manhattanLength() < 5: return char = self.board.getData(self.clickedSquare.x(), self.clickedSquare.y()) if char[0] != self.currentPlayer: return if char != ' ': icon = self.piece(char) if icon.isNull(): return self.showLegalMoves() iconPosition = self.squareRect(self.clickedSquare.x(), self.clickedSquare.y(), self.orientation[0]).topLeft() offset = QPoint(event.pos() - iconPosition) # Pixmap shown under cursor while dragging dpr = 2 # device pixel ratio pixmap = icon.pixmap( QSize(self.squareSize.width() * dpr, self.squareSize.height() * dpr)) pixmap.setDevicePixelRatio(dpr) # Serialize drag-drop data into QByteArray data = QByteArray() dataStream = QDataStream(data, QIODevice.WriteOnly) dataStream << icon << offset # Custom MIME data mimeData = QMimeData() mimeData.setData('dragdrop', data) # Drag action drag = QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(pixmap) drag.setHotSpot( QPoint(self.squareSize.width() / 2, self.squareSize.height() / 2)) self.maskedSquare = self.clickedSquare self.dragStarted.emit(self.clickedSquare) drag.exec_() self.maskedSquare = None
def mimeData(self, list_of_QModelIndex): valid_rows = [] for index in list_of_QModelIndex: # create a list of Presentation tuples showing how layers are presented if index.isValid(): valid_rows.append((index.row(), self.doc.current_layer_set[index.row()])) p = pkl.dumps((len(self.doc.current_layer_set), valid_rows), pkl.HIGHEST_PROTOCOL) mime = QMimeData() # t = base64.encodebytes(p).decode('ascii') # LOG.debug('mimetext for drag is "{}"'.format(t)) mime.setData(self._mimetype, p) LOG.debug('presenting mime data for {0!r:s}'.format(valid_rows)) return mime
def mousePressEvent(self, event): mimeData = QMimeData() b = bytearray() b.extend(self._ident.encode()) mimeData.setData('logo/ident', b) mimeData.setText(self._ident) drag = QDrag(self) drag.setPixmap(self.pixmap()) drag.setMimeData(mimeData) drag.setHotSpot(event.pos() - self.rect().topLeft()) drag.exec(Qt.CopyAction | Qt.CopyAction, Qt.CopyAction)
def mouseMoveEvent(self, event): # if the left mouse button is used if self.drag_started: data = QByteArray() mime_data = QMimeData() mime_data.setData(self.mimetext, data) drag = QDrag(self) drag.setMimeData(mime_data) drag.setPixmap(self.icon.get_icon()) drag.setHotSpot(self.rect().topLeft()) # where do we drag from if drag.exec_(Qt.MoveAction): self.parent().icons.remove(self) self.deleteLater()
def mimeData(self, indexes): mimeData = QMimeData() encodedData = QByteArray() stream = QDataStream(encodedData, QIODevice.WriteOnly) for index in indexes: if index.isValid(): pixmap = QPixmap(self.data(index, Qt.UserRole)) location = self.data(index, Qt.UserRole + 1) stream << pixmap << location mimeData.setData("image/x-puzzle-piece", encodedData) return mimeData
def encodeMimeData(self, items): data = QByteArray() stream = QDataStream(data, QIODevice.WriteOnly) for column, label in items: stream.writeInt32(0) stream.writeInt32(column) stream.writeInt32(2) stream.writeInt32(int(Qt.DisplayRole)) stream.writeQVariant(label) stream.writeInt32(int(Qt.UserRole)) stream.writeQVariant(column) mimedata = QMimeData() mimedata.setData(MyHeader.MimeType, data) return mimedata
def get_mime(self): """ return a copy of this widget's mime data Returns ------- Qt Mime data from this widget """ mime_data = QMimeData() pretty_xml = etree.tostring(self.to_xml(), pretty_print=True).decode() mime_data.setText(pretty_xml) mime_data.setData('application/x-qt-windows-mime;value="XML"', QByteArray(pretty_xml.encode())) return mime_data
def execute(self, script_variable): cur_path = script_variable["cur_path"] file_list = script_variable["file_list"] files = "" for f in file_list: files += "file://" + cur_path + "/" + f + "\r\n" mimeData = QMimeData() mimeData.setData("text/uri-list", files.encode()) clipboard = QApplication.clipboard() clipboard.setMimeData(mimeData) print("成功复制到剪切板", files)
def mouseMoveEvent(self, event): """ Protected method to handle mouse move events. @param event reference to the mouse move event (QMouseEvent) """ if event.buttons() == Qt.MouseButtons(Qt.LeftButton) and \ (event.pos() - self.__dragStartPos).manhattanLength() > \ QApplication.startDragDistance(): drag = QDrag(self) mimeData = QMimeData() index = self.tabAt(event.pos()) mimeData.setText(self.tabText(index)) mimeData.setData("action", b"tab-reordering") mimeData.setData("tabbar-id", str(id(self)).encode("utf-8")) mimeData.setData( "source-index", QByteArray.number(self.tabAt(self.__dragStartPos))) mimeData.setData("tabwidget-id", str(id(self.parentWidget())).encode("utf-8")) drag.setMimeData(mimeData) if event.modifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier): drag.exec_(Qt.DropActions(Qt.CopyAction)) elif event.modifiers() == Qt.KeyboardModifiers(Qt.NoModifier): drag.exec_(Qt.DropActions(Qt.MoveAction)) super(TabBar, self).mouseMoveEvent(event)
def mouseMoveEvent(self, event): """ Protected method to handle mouse move events. @param event reference to the mouse move event (QMouseEvent) """ if event.buttons() == Qt.MouseButtons(Qt.LeftButton) and \ (event.pos() - self.__dragStartPos).manhattanLength() > \ QApplication.startDragDistance(): drag = QDrag(self) mimeData = QMimeData() index = self.tabAt(event.pos()) mimeData.setText(self.tabText(index)) mimeData.setData("action", b"tab-reordering") mimeData.setData("tabbar-id", str(id(self)).encode("utf-8")) mimeData.setData( "source-index", QByteArray.number(self.tabAt(self.__dragStartPos))) mimeData.setData( "tabwidget-id", str(id(self.parentWidget())).encode("utf-8")) drag.setMimeData(mimeData) if event.modifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier): drag.exec_(Qt.DropActions(Qt.CopyAction)) elif event.modifiers() == Qt.KeyboardModifiers(Qt.NoModifier): drag.exec_(Qt.DropActions(Qt.MoveAction)) super(TabBar, self).mouseMoveEvent(event)
def mimeData(self, indexes): mimeData = QMimeData() encodedData = QByteArray() stream = QDataStream(encodedData, QIODevice.WriteOnly) for index in indexes: if index.isValid(): pixmap = QPixmap(self.data(index, Qt.UserRole)) location = self.data(index, Qt.UserRole + 1) stream << pixmap << location mimeData.setData('image/x-puzzle-piece', encodedData) return mimeData
def copyAsComponent(self): glyphs = self.glyphCellView.glyphs() pickled = [] for index in self.glyphCellView.selection(): glyph = glyphs[index] componentGlyph = glyph.__class__() componentGlyph.width = glyph.width component = componentGlyph.instantiateComponent() component.baseGlyph = glyph.name pickled.append(componentGlyph.serialize()) clipboard = QApplication.clipboard() mimeData = QMimeData() mimeData.setData("application/x-trufont-glyph-data", pickle.dumps(pickled)) clipboard.setMimeData(mimeData)
def mimeData(self, indexes): mimeData = QMimeData() encodedData = "" root = ET.Element("outlineItems") for index in indexes: if index.isValid() and index.column() == 0: item = ET.XML(index.internalPointer().toXML()) root.append(item) encodedData = ET.tostring(root) mimeData.setData("application/xml", encodedData) return mimeData
def keyPressEvent(self, event): if(event.key() == Qt.Key_C and event.modifiers() & Qt.ControlModifier): indexes = self.selectionModel().selectedIndexes() previous = indexes[0] values = QByteArray() for index in sorted(indexes): if index.row() != previous.row(): values += '\n' elif index != indexes[0]: values += '\t' values += self.itemFromIndex(index).text() previous = index mimeData = QMimeData() mimeData.setData("text/plain", values) QApplication.clipboard().setMimeData(mimeData) else: return QTableWidget.keyPressEvent(self, event)
def mouseMoveEvent(self, event): """ Protected method to handle mouse move events. @param event reference to the mouse move event (QMouseEvent) """ if event.buttons() == Qt.MouseButtons(Qt.LeftButton) and \ (event.pos() - self.__dragStartPos).manhattanLength() > \ QApplication.startDragDistance(): drag = QDrag(self) mimeData = QMimeData() index = self.tabAt(event.pos()) mimeData.setText(self.tabText(index)) mimeData.setData("action", "tab-reordering") mimeData.setData("tabbar-id", str(id(self))) drag.setMimeData(mimeData) drag.exec_() E5WheelTabBar.mouseMoveEvent(self, event)
def mousePressEvent(self, event): itemData = QByteArray() dataStream = QDataStream(itemData, QIODevice.WriteOnly) dataStream << QByteArray(self.labelText) << QPoint(event.pos() - self.rect().topLeft()) mimeData = QMimeData() mimeData.setData("application/x-fridgemagnet", itemData) mimeData.setText(self.labelText) drag = QDrag(self) drag.setMimeData(mimeData) drag.setHotSpot(event.pos() - self.rect().topLeft()) drag.setPixmap(self.pixmap()) self.hide() if drag.exec_(Qt.MoveAction | Qt.CopyAction, Qt.CopyAction) == Qt.MoveAction: self.close() else: self.show()
def mimeData(self, indexes): """Returns dragged data as MIME data""" mime_data = QMimeData() """set MIME type""" mime_data.setData(self.MIME_TYPE, QByteArray()) """row index is just a pair of item parent and row number""" row_indexes = [] for index in indexes: item = self.itemFromIndex(index) parent = item.parent() if parent is None: parent = self.invisibleRootItem() row_indexes.append((parent, item.row())) def copyRowWithChildren(row_index): """copy row and its children except for those that are in row_indexes to avoid duplicates""" parent, row_i = row_index row = [] for column_i in range(parent.columnCount()): original = parent.child(row_i, column_i) copy = original.clone() for child_row_i in range(original.rowCount()): child_row_index = (original, child_row_i) if child_row_index not in row_indexes: child_row = copyRowWithChildren(child_row_index) copy.appendRow(child_row) row.append(copy) return row rows = [] for i in row_indexes: """copy not move, because these rows will be deleted automatically after dropMimeData""" rows.append(copyRowWithChildren(i)) """mime_data.rows available only in the application""" mime_data.rows = rows return mime_data
def startDrag(self, supportedActions): item = self.currentItem() itemData = QByteArray() dataStream = QDataStream(itemData, QIODevice.WriteOnly) pixmap = QPixmap(item.data(Qt.UserRole)) location = item.data(Qt.UserRole+1) dataStream << pixmap << location mimeData = QMimeData() mimeData.setData('image/x-puzzle-piece', itemData) drag = QDrag(self) drag.setMimeData(mimeData) drag.setHotSpot(QPoint(pixmap.width()/2, pixmap.height()/2)) drag.setPixmap(pixmap) if drag.exec_(Qt.MoveAction) == Qt.MoveAction: if self.currentItem() is not None: self.takeItem(self.row(item))
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 mouseMoveEvent(self, event): if self.parent() is not self.parent().src_dragwidget: for item in self.parent().src_selected: item.icon.deselect_icon() self.parent().clear_dnd() # if self.drag_started: data = QByteArray() mime_data = QMimeData() mime_data.setData(self.mimetext, data) drag = QDrag(self) drag.setMimeData(mime_data) drag.setPixmap(self.icon.get_icon()) drag.setHotSpot(self.rect().topLeft()) if drag.exec_(Qt.MoveAction): if len(self.parent().src_selected) > 0: for item in self.parent().src_selected: self.parent().icons.remove(item) item.deleteLater() else: self.parent().icons.remove(self) self.deleteLater() self.parent().clear_dnd()
def mousePressEvent(self, event): square = self.targetSquare(event.pos()) found = self.findPiece(square) if found == -1: return location = self.pieceLocations[found] pixmap = self.piecePixmaps[found] del self.pieceLocations[found] del self.piecePixmaps[found] del self.pieceRects[found] if location == QPoint(square.x() / 80, square.y() / 80): self.inPlace -= 1 self.update(square) itemData = QByteArray() dataStream = QDataStream(itemData, QIODevice.WriteOnly) dataStream << pixmap << location mimeData = QMimeData() mimeData.setData('image/x-puzzle-piece', itemData) drag = QDrag(self) drag.setMimeData(mimeData) drag.setHotSpot(event.pos() - square.topLeft()) drag.setPixmap(pixmap) if drag.exec_(Qt.MoveAction) != Qt.MoveAction: self.pieceLocations.insert(found, location) self.piecePixmaps.insert(found, pixmap) self.pieceRects.insert(found, square) self.update(self.targetSquare(event.pos())) if location == QPoint(square.x() / 80, square.y() / 80): self.inPlace += 1
def mimeData(self, indices): row = -1 for index in indices: # Only generate mime data on command rows if (index.row() < 0 or index.row() >= self.mCommands.size()): return None # Currently only one row at a time is supported for drags # Note: we can get multiple indexes in the same row (different columns) if (row != -1 and index.row() != row): return None row = index.row() command = self.mCommands[row] mimeData = QMimeData() # Text data is used if command is dragged to a text editor or terminal mimeData.setText(command.finalCommand()) # Ptr is used if command is dragged onto another command # We could store the index instead, the only difference would be that if # the item is moved or deleted shomehow during the drag, the ptr approach # will result in a no-op instead of moving the wrong thing. addr = command mimeData.setData(commandMimeType, QByteArray(addr, 4)) return mimeData
def mimeData(self, items): mimeData = QMimeData() encodedData = "" root = ET.Element("outlineItems") for item in items: plotID = item.data(0, Qt.UserRole) subplotRaw = item.parent().indexOfChild(item) _id, name, summary = self._model.getSubPlotsByID(plotID)[subplotRaw] sub = ET.Element("outlineItem") sub.set(Outline.title.name, name) sub.set(Outline.type.name, settings.defaultTextType) sub.set(Outline.summaryFull.name, summary) sub.set(Outline.notes.name, self.tr("**Plot:** {}").format( Ref.plotReference(plotID))) root.append(sub) encodedData = ET.tostring(root) mimeData.setData("application/xml", encodedData) return mimeData
def mimeData(self, indexes): rows = set(str(index.row()) for index in indexes) data = ','.join(rows) mimeData = QMimeData() mimeData.setData(MIME_INDEXES, QByteArray(data.encode())) return mimeData
def _handle_copy_binary(self): mime = QMimeData() # mime type suggested here: http://stackoverflow.com/a/6783972/87207 mime.setData("application/octet-stream", self._selected_data) QApplication.clipboard().setMimeData(mime)