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() & QtCore.Qt.LeftButton: return if (event.pos() - self.dragStartPosition).manhattanLength() \ < QtGui.QApplication.startDragDistance(): return if not self.hasImage: return drag = QtGui.QDrag(self) mimeData = QtCore.QMimeData() output = QtCore.QByteArray() outputBuffer = QtCore.QBuffer(output) outputBuffer.open(QtCore.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, QtCore.Qt.KeepAspectRatio)) drag.setHotSpot(QtCore.QPoint(drag.pixmap().width() / 2, drag.pixmap().height())) drag.start()
def mouseMoveEvent(self, e): """ Start a drag operation and drop it if it was accepted by item overview Arguments: e -- a mouse event """ if e.buttons() != QtCore.Qt.LeftButton: return mimedata = QtCore.QMimeData() mimedata.setText("__osnew__ %s" % self.item) drag = QtGui.QDrag(self) drag.setMimeData(mimedata) drag.setHotSpot(e.pos() - self.rect().topLeft()) drag.setPixmap(self.pixmap) if drag.start(QtCore.Qt.CopyAction) == QtCore.Qt.CopyAction: if self.item == "loop": self.main_window.drop_item(self.main_window.add_loop) elif self.item == "sequence": self.main_window.drop_item(self.main_window.add_sequence) else: self.main_window.drop_item(self.item) else: debug.msg("drop cancelled")
def performSingleClickAction(self): self.bTimer = False if self.bDoubleClick: return label = self.__getLabelName() #= self.childAt(self.event.pos()) if not label: return mimeData = QtCore.QMimeData() indices = self.selectedIndexes() if len(indices) > 0: index = indices[0] item = self.model().item(index.row(), 0) labelName = item.getFullSignalName() mimeData.setText(labelName) labelNameList = labelName.split("|") qlabel = QtGui.QLabel(labelNameList[0]) pixmap = QtGui.QPixmap(qlabel.size()) qlabel.render(pixmap) drag = QtGui.QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(pixmap) dropAction = drag.exec_( QtCore.Qt.CopyAction | QtCore.Qt.MoveAction, QtCore.Qt.CopyAction) if dropAction == QtCore.Qt.MoveAction: label.close()
def mouseMoveEvent(self, e): QtGui.QListView.mouseMoveEvent(self, e) print "call mouseMove" # if e.buttons() != QtCore.Qt.RightButton: # return # write the relative cursor position to mime data mimeData = QtCore.QMimeData() # simple string with 'x,y' mimeData.setText('%d,%d' % (e.x(), e.y())) # let's make it fancy. we'll show a "ghost" of the button as we drag # grab the button to a pixmap pixmap = self.create_mini_pixmap() # make a QDrag drag = QtGui.QDrag(self) # put our MimeData drag.setMimeData(mimeData) # set its Pixmap drag.setPixmap(pixmap) # shift the Pixmap so that it coincides with the cursor position drag.setHotSpot(QtCore.QPoint(0, 0)) print 'source : ', drag.source(), ' dest : ', drag.target() # start the drag operation # exec_ will return the accepted action from dropEvent a = drag.exec_(QtCore.Qt.CopyAction | QtCore.Qt.MoveAction) if a == QtCore.Qt.MoveAction: print 'moved' else: print 'copied' print "drop action : ", a print "copy - move", QtCore.Qt.CopyAction, QtCore.Qt.MoveAction print 'source : ', drag.source(), ' dest : ', drag.target()
def startDrag(self, event): # item is of type NodeListItem item = self.currentItem() # nodeData is the data (BaseNode type) that item was created with nodeData = nt.NodeTypes[item.dictKey] #nodeData = mayaNodesModule.MayaNodes[item.dictKey]) i = id(nodeData) self.d[i] = nodeData pickleData = cPickle.dumps(i) data = QtCore.QByteArray.fromRawData(pickleData) mimeData = QtCore.QMimeData() mimeData.setData("application/x-imgname", data) drag = QtGui.QDrag(self) drag.setMimeData(mimeData) # Setting the icon that the mouse cursor displays icon = item.icon() pixmap = icon.pixmap(48, 48) drag.setPixmap(pixmap.scaled(pixmap.height() * .5, pixmap.width() * .5)) # Actually starts the dragging drag.exec_()
def graphicsMouseMoveEvent(self, event, itemId=0): """This function is called by the owned TrackGraphicsItem to handle its mouseMoveEvent. Reimplemented in the ResizableItem class to begin a drag operation on corners.""" if event.buttons() == Qt.LeftButton and \ self.simulation.context == utils.Context.EDITOR_SCENERY: if QtCore.QLineF(event.scenePos(), event.buttonDownScenePos(Qt.LeftButton)).length() \ < 3.0: return drag = QtGui.QDrag(event.widget()) mime = QtCore.QMimeData() pos = event.buttonDownScenePos(Qt.LeftButton) - self.origin if QtCore.QRectF(-5, -5, 9, 9).contains(pos): movedEnd = "start" elif QtCore.QRectF(self.end.x() - self.origin.x() - 5, self.end.y() - self.origin.y() - 5, 9, 9).contains(pos): movedEnd = "end" pos -= self.end - self.origin #elif self._gi[itemId].shape().contains(pos): else: movedEnd = "origin" if movedEnd is not None: mime.setText(self.tiType + "#" + str(self.tiId) + "#" + str(pos.x()) + "#" + str(pos.y()) + "#" + movedEnd) drag.setMimeData(mime) drag.exec_()
def send(drag_src, data): """ desc: Starts a drag event, and embeds a data dictionary as json text in the mimedata. arguments: drag_src: desc: The source widget. type: QWidget data: desc: A data dictionary. The 'type' key identifies the type of data that is being dropped. type: dict returns: desc: A drag object. The start function is called automatically. type: QDrag """ text = json.dumps(data).decode('utf-8') mimedata = QtCore.QMimeData() mimedata.setText(text) drag = QtGui.QDrag(drag_src) drag.setMimeData(mimedata) drag.start()
def pressItem(self, item): self.topLevelWidget().basket.show() #itemdata = repr(item.data(Qt.Qt.UserRole)) mimeData = QtCore.QMimeData() mimeData.setText(item.text()) if item == self.selectedItem: id = item.data(Qt.Qt.UserRole)['id'] row = item.listWidget().row(item) mimeData.setData('application/ok-case', '{"id":"%s","row":"%d"}' % (id, row)) itemIndex = self.indexFromItem(item) itemRect = self.visualRect(itemIndex) pixmap = Qt.QPixmap(itemRect.size()) self.render(pixmap, QtCore.QPoint(0, 0), Qt.QRegion(itemRect)) drag = Qt.QDrag(self) drag.setMimeData(mimeData) drag.setHotSpot(QtCore.QPoint(pixmap.width() / 2, pixmap.height() / 2)) drag.setPixmap(pixmap) dropAction = drag.exec_(QtCore.Qt.CopyAction | QtCore.Qt.MoveAction, QtCore.Qt.CopyAction) self.topLevelWidget().basket.hide() if dropAction == QtCore.Qt.MoveAction: self.close() self.update()
def start_drag(self): """Begin a drag and drop event""" drag = QtGui.QDrag(self) mimeData = QtCore.QMimeData() mimeData.setData("text/plain", self.prop['kid']) drag.setMimeData(mimeData) drag.exec_()
def mousePressEvent(self, event): child = self.childAt(event.pos()) if not child: return pixmap = QtGui.QPixmap(child.pixmap()) itemData = QtCore.QByteArray() dataStream = QtCore.QDataStream(itemData, QtCore.QIODevice.WriteOnly) dataStream << pixmap << QtCore.QPoint(event.pos() - child.pos()) mimeData = QtCore.QMimeData() mimeData.setData('application/x-dnditemdata', itemData) drag = QtGui.QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(pixmap) drag.setHotSpot(event.pos() - child.pos()) tempPixmap = QtGui.QPixmap(pixmap) painter = QtGui.QPainter() painter.begin(tempPixmap) painter.fillRect(pixmap.rect(), QtGui.QColor(127, 127, 127, 127)) painter.end() child.setPixmap(tempPixmap) if drag.exec_(QtCore.Qt.CopyAction | QtCore.Qt.MoveAction, QtCore.Qt.CopyAction) == QtCore.Qt.MoveAction: child.close() else: child.show() child.setPixmap(pixmap)
def mimeData(self, indexList): """Return a mime data object for the given node index branches. Arguments: indexList -- a list of node indexes to convert """ allNodes = [index.internalPointer() for index in indexList] nodes = [] # accept only nodes on top of unique branches for node in allNodes: parent = node.parent while parent and parent not in allNodes: parent = parent.parent if not parent: nodes.append(node) TreeModel.storedDragNodes = nodes TreeModel.storedDragModel = self dummyFormat = None if len(nodes) > 1: dummyFormat = self.formats.addDummyRootType() root = treenode.TreeNode(None, dummyFormat.name, self) for node in nodes: root.childList.append(copy.copy(node)) root.childList[-1].parent = root else: root = nodes[0] text = ElementTree.tostring( root.elementXml({dummyFormat}, True, False), 'utf-8') self.formats.removeDummyRootType() mime = QtCore.QMimeData() mime.setData('text/xml', text) return mime
def _show_drag_text(self, widget): text = self._text_map.get(widget) # Put the text into the clipboard self._clipboard.clear() self._clipboard.setText(text, mode=QtGui.QClipboard.Selection) # Create a label for the "drag" display label = QtGui.QLabel() label.setStyleSheet(self._select_style_sheet) label.setSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored) label.setFont(self._select_font) label.setText(text) # Must use this invocation to get boundingRect to interpret newlines rect = label.fontMetrics().boundingRect(0, 0, 1000, 1000, 0, text) # Create pixmap and render label onto it pixmap = QtGui.QPixmap(rect.width(), rect.height()) label.render(pixmap) drag = QtGui.QDrag(self) drag.setPixmap(pixmap) # Does not seem to work without mimeData mime_data = QtCore.QMimeData() drag.setMimeData(mime_data) # Start the drag drag.exec_(QtCore.Qt.CopyAction | QtCore.Qt.MoveAction, QtCore.Qt.CopyAction)
def mouseMoveEvent(self, event): if self.lastClick[0]: if (self.lastClick[1].x() - event.pos().x())**2 + ( self.lastClick[1].y() - event.pos().y())**2 > 5: if self.lastClick[2] != -1: selectedSlot = self.slots[self.lastClick[2]] selectedItem = selectedSlot.item if selectedItem != None: drag = QtGui.QDrag(self) mimeData = QtCore.QMimeData() mimeData.setText(selectedItem.text() + ";" + selectedItem.identifier + ";" + str(selectedSlot.count)) pixmap = selectedItem.texture.scaled(50, 50) painter = QtGui.QPainter(pixmap) painter.setCompositionMode( painter.CompositionMode_DestinationIn) painter.fillRect(pixmap.rect(), QtGui.QColor(0, 0, 0, 127)) painter.end() drag.setMimeData(mimeData) drag.setPixmap(pixmap) self.slots[self.lastClick[2]].item = None self.slots[self.lastClick[2]].count = 0 drag.exec_(QtCore.Qt.MoveAction)
def copyCurrentCell(self): index = self.currentIndex() if index.isValid(): carrier = QtCore.QMimeData() dataAsText = self.model().data(index, QtCore.Qt.DisplayRole) carrier.setText(dataAsText.toString() if dataAsText else '' ) QtGui.qApp.clipboard().setMimeData(carrier)
def startDrag(self, event): index = self.indexAt(event.pos()) if not index.isValid(): return # # selected is the relevant person object selected = self.model().data(index, QtCore.Qt.UserRole) # # convert to a bytestream bstream = cPickle.dumps(selected) mimeData = QtCore.QMimeData() mimeData.setData("application/x-person", bstream) drag = QtGui.QDrag(self) drag.setMimeData(mimeData) # example 1 - the object itself pixmap = QtGui.QPixmap() pixmap = pixmap.grabWidget(self, self.rectForIndex(index)) # example 2 - a plain pixmap # pixmap = QtGui.QPixmap(100, self.height()/2) # pixmap.fill(QtGui.QColor("orange")) drag.setPixmap(pixmap) drag.setHotSpot(QtCore.QPoint(pixmap.width() / 2, pixmap.height() / 2)) drag.setPixmap(pixmap) result = drag.start(QtCore.Qt.MoveAction) if result: # == QtCore.Qt.MoveAction: self.model().removeRow(index.row())
def mouseMoveEvent(self, e): drag = QtGui.QDrag(self) mimeData = QtCore.QMimeData() drag.setMimeData(mimeData) drag.setPixmap(QtGui.QPixmap.fromImage(self.createPixmap())) dropAction = drag.start(QtCore.Qt.MoveAction)
def mimeData(self, indexes): """Returns an object that contains serialized items of data corresponding to the list of indexes specified. When a node is dragged the information required to drop it later on is encoded by this method and returned as a QMimeData object. :Parameter indexes: a list of indexes """ mime_data = QtCore.QMimeData() encoded_data = QtCore.QByteArray() stream = QtCore.QDataStream(encoded_data, QtCore.QIODevice.WriteOnly) # Only one item selections are allowed in the tree of databases # view so indexes contains always one element for index in indexes: if index.isValid(): filepath = self.data(index, QtCore.Qt.UserRole) nodepath = self.data(index, QtCore.Qt.UserRole + 1) row = unicode(index.row()) stream.writeQString(filepath) stream.writeQString(nodepath) stream.writeQString(row) self.initial_parent = self.parent(index) mime_data.setData("application/x-dbstreemodeldatalist", encoded_data) return mime_data
def _dragdrop(self, e): mimeData = QtCore.QMimeData() mimeData.setColorData(self.color) drag = QtGui.QDrag(self) drag.setMimeData(mimeData) drag.setHotSpot(e.pos() - self.rect().topLeft()) dropAction = drag.start(QtCore.Qt.MoveAction)
def start_drag(self): drag = QtGui.QDrag(self) mimeData = QtCore.QMimeData() ds = self.doc.data.get('0:kiln/Ts', False) if ds is False: ds = self.doc.data.get('0:kiln/T') T = ds.data[self.doc_idx] # Text copy mimeData.setData( "text/plain", 'point:{}:{}:{}'.format(self.base_dataset_path, self.t, T)) # Image copy ba = QtCore.QByteArray() buf = QtCore.QBuffer(ba) buf.open(QtCore.QIODevice.WriteOnly) self.img.save(buf, 'PNG') mimeData.setData("image/png", ba) ba1 = QtCore.QByteArray() buf1 = QtCore.QBuffer(ba1) buf1.open(QtCore.QIODevice.WriteOnly) self.img.save(buf1, 'BMP') mimeData.setData("image/bmp", ba1) # File copy name = '{}_{}.png'.format( self.base_dataset_path.replace('/', '_').replace(':', ''), self.idx) name = os.path.join(self.decoder.tmpdir, name) self.img.save(name, 'PNG') mimeData.setData("text/uri-list", "file:///" + name) mimeData.setImageData(self.img) drag.setMimeData(mimeData) drag.setPixmap(self.lbl_img.pixmap()) logging.debug('start drag', mimeData.text()) drag.exec_()
def on_copyimg(self): # Take a screenshot: w2if = vtk.vtkWindowToImageFilter() w2if.SetInput(self.renderWindowInteractor.GetRenderWindow()) w2if.Update() # screenshot is a vtk_widget object image = w2if.GetOutput() # write a temp image file writer = vtk.vtkPNGWriter() writer.SetFileName("tempfile.png") writer.SetInput(image) writer.Write() # read the temp image file ### This works... copying image from file to clipboard self.clipboard = QtGui.QApplication.clipboard() data = QtCore.QMimeData() #data.setImageData(QtGui.QImage(r'D:\PGM\01_DEV\VTK\MVC\1.png')) data.setImageData(QtGui.QImage("tempfile.png")) self.clipboard.setMimeData(data) # remove the tempfile os.remove("tempfile.png")
def mouseMoveEvent(self, e): QtGui.QToolButton.mouseMoveEvent(self, e) if e.buttons() == QtCore.Qt.LeftButton and self.dragStartPoint: x, y = e.x(), e.y() ox, oy = self.dragStartPoint dx2 = (x - ox)**2 dy2 = (y - oy)**2 d2 = dx2 + dy2 if d2 > MIN_DRAG_DISTANCE**2: mimeData = QtCore.QMimeData() mimeData.setText(self.key) drag = QtGui.QDrag(self) drag.setPixmap(self.icon().pixmap(16, 16)) drag.setMimeData(mimeData) dragstartQPoint = QtCore.QPoint(self.dragStartPoint[0], self.dragStartPoint[1]) drag.setHotSpot(dragstartQPoint - self.rect().topLeft()) self.parent.layout().removeWidget(self) self.parent.keys.remove(self.key) self.parent.parent.prjconn.call.updateDirectLinks( self.parent.keys) self.hide() dropAction = drag.start(QtCore.Qt.MoveAction) if (self.parent.layout().count() <= 1): self.parent.dragInfoLabel.show()
def mouseMoveEvent(self, e): # if e.buttons() != QtCore.Qt.RightButton: # return # write the relative cursor position to mime data mimeData = QtCore.QMimeData() # simple string with 'x,y' mimeData.setText('%d,%d' % (e.x(), e.y())) # let's make it fancy. we'll show a "ghost" of the button as we drag # grab the button to a pixmap pixmap = QtGui.QPixmap.grabWidget(self) # below makes the pixmap half transparent painter = QtGui.QPainter(pixmap) painter.setCompositionMode(painter.CompositionMode_DestinationIn) painter.fillRect(pixmap.rect(), QtGui.QColor(0, 0, 0, 127)) painter.end() # make a QDrag drag = QtGui.QDrag(self) # put our MimeData drag.setMimeData(mimeData) # set its Pixmap drag.setPixmap(pixmap) # shift the Pixmap so that it coincides with the cursor position drag.setHotSpot(e.pos()) # start the drag operation # exec_ will return the accepted action from dropEvent if drag.exec_(QtCore.Qt.CopyAction | QtCore.Qt.MoveAction) == QtCore.Qt.MoveAction: print 'moved' else: print 'copied'
def startDrag(self, dropActions): item = self.currentItem() # check parent name and return if top level node if item.parent() == None: return # get dir name dirName = unicode(item.parent().text(0)) # get node from library nodeName = unicode(item.text(0)) # set custom data data = QtCore.QByteArray() stream = QtCore.QDataStream(data, QtCore.QIODevice.WriteOnly) stream << item.parent().text(0) << item.text(0) mimeData = QtCore.QMimeData() mimeData.setData('application/x-text', data) # set drag drag = QtGui.QDrag(self) drag.setMimeData(mimeData) drag.setPixmap(QtGui.QPixmap(':/node.png')) drag.start(QtCore.Qt.CopyAction)
def startDrag(self, event): index = self.indexAt(event.pos()) if not index.isValid(): return # selected is the relevant person object selectedApp = self.model().data(index, QtCore.Qt.UserRole) if not selectedApp.unscheduled: event.ignore() return if index not in self.selectedIndexes(): self.setCurrentIndex(index) # convert to a bytestream bstream = cPickle.dumps(selectedApp) mimeData = QtCore.QMimeData() mimeData.setData("application/x-appointment", bstream) drag = QtGui.QDrag(self) drag.setMimeData(mimeData) drag.setDragCursor(QtGui.QPixmap(), QtCore.Qt.MoveAction) pixmap = QtGui.QPixmap() pixmap = pixmap.grabWidget(self, self.rectForIndex(index)) drag.setPixmap(pixmap) drag.setHotSpot(QtCore.QPoint(-10, 0)) drag.start(QtCore.Qt.CopyAction)
def copy_files(self, objects): mimeData = QtCore.QMimeData() mimeData.setUrls([ QtCore.QUrl.fromLocalFile(f.filename) for f in (self.get_files_from_objects(objects)) ]) self.clipboard().setMimeData(mimeData)
def copy_to_clipboard(self): indices = self.selectedIndexes() n_columns = self.model().columnCount(0) indices.sort(key=lambda x: x.row() * n_columns + x.column()) c_row = 0 c_column = 0 html = "<table><tr>" txt = "" for index in indices: if index.isValid(): if index.row() > c_row: html += "</tr>" + "<tr>" txt += "\n" if index.column() > c_column: txt += "; " txt += str(index.data()) html += "<td>" + str(index.data()) + "</td>" c_row = index.row() c_column = index.column() html += "</tr></table>" if len(html) > 0: mime = QtCore.QMimeData() mime.setHtml(html) mime.setText(txt) QtGui.qApp.clipboard().setMimeData(mime)
def copy_selection_to_clipboard(self, selection_model): """Copy table selection to the clipboard. """ # TODO: html/rtf table import csv from io import StringIO rows = selection_model.selectedRows(0) csv_str = StringIO() csv_writer = csv.writer(csv_str, dialect="excel") tsv_str = StringIO() tsv_writer = csv.writer(tsv_str, dialect="excel-tab") for row in rows: line = [] for i in range(self.model().columnCount()): index = self.model().index(row.row(), i) val = index.data(QtCore.Qt.DisplayRole) line.append(str(val)) csv_writer.writerow(line) tsv_writer.writerow(line) csv_lines = csv_str.getvalue() tsv_lines = tsv_str.getvalue() mime = QtCore.QMimeData() mime.setData("text/csv", QtCore.QByteArray(csv_lines)) mime.setData("text/tab-separated-values", QtCore.QByteArray(tsv_lines)) mime.setData("text/plain", QtCore.QByteArray(tsv_lines)) QtGui.QApplication.clipboard().setMimeData(mime, QtGui.QClipboard.Clipboard)
def mouseMoveEvent(self, event): if event.buttons() == QtCore.Qt.LeftButton: mimeData = QtCore.QMimeData() drag = QtGui.QDrag(self) mimeData.setText('9') drag.setMimeData(mimeData) drag.setHotSpot(event.pos()) dropAction = drag.start(QtCore.Qt.MoveAction)
def mimeData(self, item): path = os.path.abspath(str(item[0].text)) print(path) if os.path.isfile(path): mimeData = QtCore.QMimeData() mimeData.setUrls([QtCore.QUrl.fromLocalFile(path)]) self.updateRecent(path) return mimeData
def _copy_color(self): color = self.get_color() if color: clipboard = QtGui.QApplication.clipboard() qcolor = color.asQColor() mime = QtCore.QMimeData() mime.setColorData(qcolor) clipboard.setMimeData(mime)