def mimeData(self, indexes): rows = list(set(index.row() for index in indexes)) if len(rows) != 1: return QtCore.QMimeData() mimedata = QtCore.QMimeData() mimedata.setData(self.MIMETYPE, str(rows[0]).encode("ascii")) return mimedata
def mimedata_from_paths(context, paths): """Return mimedata with a list of absolute path URLs The text/x-moz-list format is always included by Qt, and doing mimedata.removeFormat('text/x-moz-url') has no effect. C.f. http://www.qtcentre.org/threads/44643-Dragging-text-uri-list-Qt-inserts-garbage gnome-terminal expects utf-16 encoded text, but other terminals, e.g. terminator, prefer utf-8, so allow cola.dragencoding to override the default. """ # noqa cfg = context.cfg abspaths = [core.abspath(path) for path in paths] urls = [QtCore.QUrl.fromLocalFile(path) for path in abspaths] mimedata = QtCore.QMimeData() mimedata.setUrls(urls) paths_text = core.list2cmdline(abspaths) encoding = cfg.get('cola.dragencoding', 'utf-16') moz_text = core.encode(paths_text, encoding=encoding) mimedata.setData('text/x-moz-url', moz_text) return mimedata
def mimeData(self, indexes): """Returns a QMimeData 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 = str(index.row()) stream.writeQString(filepath) stream.writeQString(nodepath) stream.writeQString(row) self.initial_parent = self.parent(index) # Store the MIME type of the object and the encoded description of that # object in the QMimeData object mime_data.setData("application/x-dbstreemodeldatalist", encoded_data) return mime_data
def mousePressEvent(self, event): """ when a mouse button is pressed """ # a left mouse button lets the user drag the color if event.button() == QtCore.Qt.LeftButton: drag = QtGui.QDrag(self) drag.setPixmap(self.grab()) mime = QtCore.QMimeData() mime.setText(self.color) drag.setMimeData(mime) self.setStyleSheet( "background-color: lightgray; border: 2px solid gray") self.setDisabled(True) self.setText("") drag.exec() self.setText(self.color) self.setDisabled(False) if self.color in self.maps: self.setStyleSheet( "text-align: center; border: 2px solid black; " + self.getBackground()) else: self.setStyleSheet( "text-align: center; background-color: %s; border: 2px solid black" % self.color) # a right mouse button opens a color choose menu elif event.button() == QtCore.Qt.RightButton: self.openDialog()
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 = safe_decode(json.dumps(data), enc=u'utf-8') mimedata = QtCore.QMimeData() mimedata.setText(text) drag = QtGui.QDrag(drag_src) drag.setMimeData(mimedata) drag.exec_()
def test_drop_load_data(self): load_data = MagicMock() load_session = MagicMock() self.app.load_data = load_data self.app.restore_session_and_close = load_session e = MagicMock() m = QtCore.QMimeData() m.setUrls([QtCore.QUrl('test.fits')]) e.mimeData.return_value = m self.app.dropEvent(e) assert load_data.called_once_with('test.fits') assert load_session.call_count == 0 load_data.reset_mock() m = QtCore.QMimeData() m.setUrls([QtCore.QUrl('test1.fits'), QtCore.QUrl('test2.fits')]) e.mimeData.return_value = m self.app.dropEvent(e) assert load_data.called_once_with(['test1.fits', 'test2.fits']) assert load_session.call_count == 0 load_data.reset_mock() m = QtCore.QMimeData() m.setUrls([QtCore.QUrl('test.glu')]) e.mimeData.return_value = m self.app.dropEvent(e) assert load_data.call_count == 0 assert load_session.called_once_with(['test.glu']) load_data.reset_mock() m = QtCore.QMimeData() m.setUrls([QtCore.QUrl('test.glu'), QtCore.QUrl('test.fits')]) e.mimeData.return_value = m with patch('qtpy.QtWidgets.QMessageBox') as mb: self.app.dropEvent(e) assert mb.call_count == 1 assert "When dragging and dropping files" in mb.call_args[0][2] mb.reset_mock() load_data.reset_mock()
def mouseMoveEvent(self, event): """ Determine if the current movement is a drag. If it is, convert it into a QDrag. If the drag ends inside the tab bar, emit an onMoveTabSignal. If the drag ends outside the tab bar, emit an onDetachTabSignal. :param event: a mouse move event. """ # Determine if the current movement is detected as a drag if not self.drag_start_pos.isNull() and ( (event.pos() - self.drag_start_pos).manhattanLength() < QtWidgets.QApplication.startDragDistance()): self.drag_initiated = True # If the current movement is a drag initiated by the left button if (event.buttons() & QtCore.Qt.LeftButton) and self.drag_initiated: # Stop the move event finish_move_event = QtGui.QMouseEvent(QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier) QtWidgets.QTabBar.mouseMoveEvent(self, finish_move_event) # Convert the move event into a drag drag = QtGui.QDrag(self) mime_data = QtCore.QMimeData() drag.setMimeData(mime_data) if PYQT4: pixmap = QtGui.QPixmap.grabWindow(self.parentWidget().currentWidget().winId()) else: app = QtWidgets.QApplication.instance() desktop = app.desktop() screen_number = desktop.screenNumber(self.parentWidget().currentWidget()) screen = app.screens()[screen_number] # Create the appearance of dragging the tab content pixmap = QtGui.QScreen.grabWindow(screen, self.parentWidget().currentWidget().winId()) target_pixmap = QtGui.QPixmap(pixmap.size()) target_pixmap.fill(QtCore.Qt.transparent) painter = QtGui.QPainter(target_pixmap) painter.setOpacity(0.85) painter.drawPixmap(0, 0, pixmap) painter.end() drag.setPixmap(target_pixmap) # Initiate the drag drop_action = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction) # For Linux: Here, drag.exec_() will not return MoveAction on Linux. So it # must be set manually if self.drag_end_pos.x() != 0 and self.drag_end_pos.y() != 0: drop_action = QtCore.Qt.MoveAction # If the drag completed inside the tab bar, move the selected tab to the new position if drop_action == QtCore.Qt.MoveAction: if not self.drag_end_pos.isNull(): event.accept() self.onMoveTabSignal.emit(self.tabAt(self.drag_start_pos), self.tabAt(self.drag_end_pos)) else: QtWidgets.QTabBar.mouseMoveEvent(self, event)
def test_drop_load_data(self): load_data = MagicMock() load_session = MagicMock() self.app.load_data = load_data self.app.restore_session_and_close = load_session e = MagicMock() m = QtCore.QMimeData() m.setUrls([QtCore.QUrl('test.fits')]) e.mimeData.return_value = m self.app.dropEvent(e) assert load_data.called_once_with('test.fits') assert load_session.call_count == 0 load_data.reset_mock() m = QtCore.QMimeData() m.setUrls([QtCore.QUrl('test1.fits'), QtCore.QUrl('test2.fits')]) e.mimeData.return_value = m self.app.dropEvent(e) assert load_data.called_once_with(['test1.fits', 'test2.fits']) assert load_session.call_count == 0 load_data.reset_mock() m = QtCore.QMimeData() m.setUrls([QtCore.QUrl('test.glu')]) e.mimeData.return_value = m self.app.dropEvent(e) assert load_data.call_count == 0 assert load_session.called_once_with(['test.glu']) load_data.reset_mock() m = QtCore.QMimeData() m.setUrls([QtCore.QUrl('test.glu'), QtCore.QUrl('test.fits')]) e.mimeData.return_value = m with pytest.raises(Exception) as exc: self.app.dropEvent(e) assert exc.value.args[0].startswith("When dragging and dropping files") load_data.reset_mock()
def test_drop_load_data(self): m = QtCore.QMimeData() m.setUrls([QtCore.QUrl('test.fits')]) e = MagicMock() e.mimeData.return_value = m load = MagicMock() self.app.load_data = load self.app.dropEvent(e) assert load.call_count == 1
def mouseMoveEvent(self, event): # Determine if the current movement is detected as a drag if not self.dragStartPos.isNull() and ( (event.pos() - self.dragStartPos).manhattanLength() > QtWidgets.QApplication.startDragDistance()): self.dragInitiated = True # If the current movement is a drag initiated by the left button if (((event.buttons() & QtCore.Qt.LeftButton)) and self.dragInitiated): # Stop the move event finishMoveEvent = QtGui.QMouseEvent(QtCore.QEvent.MouseMove, event.pos(), QtCore.Qt.NoButton, QtCore.Qt.NoButton, QtCore.Qt.NoModifier) super().mouseMoveEvent(finishMoveEvent) # Convert the move event into a drag drag = QtGui.QDrag(self) mimeData = QtCore.QMimeData() mimeData.setData('action', b'application/tab-detach') drag.setMimeData(mimeData) #Create the appearance of dragging the tab content pixmap = self.parentWidget().grab() targetPixmap = QtGui.QPixmap(pixmap.size()) targetPixmap.fill(QtCore.Qt.transparent) painter = QtGui.QPainter(targetPixmap) painter.setOpacity(0.85) painter.drawPixmap(0, 0, pixmap) painter.end() drag.setPixmap(targetPixmap) # Initiate the drag dropAction = drag.exec_(QtCore.Qt.MoveAction | QtCore.Qt.CopyAction) # If the drag completed outside of the tab bar, detach the tab and move # the content to the current cursor position if dropAction == QtCore.Qt.IgnoreAction: event.accept() self.onDetachTabSignal.emit(self.tabAt(self.dragStartPos), self.mouseCursor.pos()) # Else if the drag completed inside the tab bar, move the selected tab to the new position elif dropAction == QtCore.Qt.MoveAction: if not self.dragDropedPos.isNull(): event.accept() self.onMoveTabSignal.emit( self.tabAt(self.dragStartPos), self.tabAt(self.dragDropedPos)) else: super().mouseMoveEvent(event)
def _on_copy(self): data = self._get_data() buffer = io.StringIO() writer = csv.writer(buffer, lineterminator="\n", delimiter="\t") writer.writerows(data) data = QtCore.QMimeData() data.setText(buffer.getvalue()) QtGui.QGuiApplication.instance().clipboard().setMimeData(data)
def copyURL(self): if not self.targetSceneNode: return cameraState = self.canvas.callMethod('view', 'saveCameraStateToString') path = self.targetSceneNode.getPath() url = self.getApp().makeURL('scene', path=path, camera=cameraState) #TODO: position mime = QtCore.QMimeData() mime.setUrls([QtCore.QUrl(url)]) mime.setText(url) clipboard = QtWidgets.QApplication.clipboard() clipboard.setMimeData(mime)
def mouseMoveEvent(self, event: QtGui.QMouseEvent): if event.buttons() != QtCore.Qt.LeftButton: event.ignore() return if (sub(event.pos(), self.dragStartPos) ).manhattanLength() < QtWidgets.QApplication.startDragDistance(): event.ignore() return self.move_me.emit(self) mime_data = QtCore.QMimeData() mime_data.setObjectName('frame') drag = QtGui.QDrag(self) drag.setMimeData(mime_data) drop_action = drag.exec_(QtCore.Qt.MoveAction)
def svg_to_clipboard(string): """ Copy a SVG document to the clipboard. Parameters ---------- string : basestring A Python string containing a SVG document. """ if isinstance(string, unicode_type): string = string.encode('utf-8') mime_data = QtCore.QMimeData() mime_data.setData('image/svg+xml', string) QtWidgets.QApplication.clipboard().setMimeData(mime_data)
def makeAssetListMimeData(assets): assetList = [] urlList = [] for asset in assets: assetList.append(asset.getPath()) if not asset.isVirtual(): urlList.append(QtCore.QUrl.fromLocalFile(asset.getAbsFilePath())) assetListData = json.dumps(assetList).encode('utf-8') text = '\n'.join(assetList) data = QtCore.QMimeData() data.setData(GII_MIME_ASSET_LIST, assetListData) if urlList: data.setUrls(urlList) data.setText(text) return data