Example #1
0
	def test_pasteImage_Markdown(self, _mock_image, _mock_editor):
		mimeData = QMimeData()
		mimeData.setImageData(self._create_image())
		self.dummytab.markupClass = MarkdownMarkup

		self.editor.insertFromMimeData(mimeData)
		self.assertTrue('![myimage](myimage.jpg)' in self.editor.toPlainText())
Example #2
0
    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)
Example #3
0
	def test_pasteImage_RestructuredText(self, _mock_image, _mock_editor):
		mimeData = QMimeData()
		mimeData.setImageData(self._create_image())
		self.dummytab.markupClass = ReStructuredTextMarkup

		self.editor.insertFromMimeData(mimeData)
		self.assertTrue('.. image:: myimage.jpg' in self.editor.toPlainText())
Example #4
0
    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)
Example #5
0
    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()
Example #6
0
 def mousePressEvent(self, event):
     mime = QMimeData()
     itemData = QByteArray()
     mime.setData('application/x-dnditemdata', itemData)
     drag = QDrag(self)
     drag.setMimeData(mime)
     drag.exec_(Qt.MoveAction)
Example #7
0
 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)
Example #9
0
    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
Example #10
0
def copy_image():
    img = QImage()
    img.loadFromData(f.read())

    data = QMimeData()
    data.setImageData(img)

    clipboard.setMimeData(data)
    print("ok")
Example #11
0
	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
Example #12
0
 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)
Example #13
0
 def __dragSnapshot(self):
     """
     Private slot handling the dragging of the preview picture.
     """
     drag = QDrag(self)
     mimeData = QMimeData()
     mimeData.setImageData(self.__snapshot)
     drag.setMimeData(mimeData)
     drag.setPixmap(self.preview.pixmap())
     drag.exec_(Qt.CopyAction)
Example #14
0
    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
Example #15
0
def dragFile(widget, filename, icon=None, dropactions=Qt.CopyAction):
    """Starts dragging the given local file from the widget."""
    if icon is None or icon.isNull():
        icon = QFileIconProvider().icon(QFileInfo(filename))
    drag = QDrag(widget)
    data = QMimeData()
    data.setUrls([QUrl.fromLocalFile(filename)])
    drag.setMimeData(data)
    drag.setPixmap(icon.pixmap(32))
    drag.exec_(dropactions)
Example #16
0
 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)
Example #17
0
 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)))
         mimeData.setData(
             "source-index",
             QByteArray.number(self.tabAt(self.__dragStartPos)))
         mimeData.setData("tabwidget-id", str(id(self.parentWidget())))
         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)
Example #18
0
 def mimeData(self, idxs):
     mdata = QMimeData()
     nodes = []
     for idx in idxs:
         item = self.itemFromIndex(idx)
         if item:
             node = item.data()
             if node:
                 nodes.append(node.nodeid.to_string())
     mdata.setText(", ".join(nodes))
     return mdata
Example #19
0
 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
Example #20
0
 def mouseMoveEvent(self, e):
     modifiers = QApplication.keyboardModifiers()
     if modifiers == Qt.ControlModifier:
         mimeData = QMimeData()
         drag = QDrag(e.widget())
         mimeData.setText("node")
         drag.setMimeData(mimeData)
         drag.exec_(Qt.MoveAction)
         self.ungrabMouse()
     if self.edgeInConstruction != None:
         self.edgeInConstruction.obsUpdate(e.scenePos())
Example #21
0
 def insertFromMimeData(self, source):
     """Remove newlines from pasted text if necessary."""
     if self.single_line:
         # Remove newlines.
         text = source.text()
         mime = QMimeData()
         # TODO:  does windows+mac work?    
         mime.setText(text.replace("\n", " "))
     else:
         mime = source
     super().insertFromMimeData(mime)
Example #22
0
 def mimeData(self, indexes):
     data = ''
     for index in indexes:
         parent_item = self.getItem(index.parent())
         if parent_item == self.rootItem:
             data += "{0},{1},{2}/".format(index.row(), index.column(), -1)
         else:
             data += "{0},{1},{2}/".format(index.row(), index.column(), self.rootItem.index_of(parent_item))
     mime_data = QMimeData()
     mime_data.setText(data)
     return mime_data
Example #23
0
 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 mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.drag_started.emit(self.mapToParent(event.pos()))
            drag = QDrag(self)
            mimeData = QMimeData()
            mimeData.setText("Move Signal")
            pixmap = QPixmap(self.rect().size())
            self.render(pixmap, QPoint(), QRegion(self.rect()))
            drag.setPixmap(pixmap)

            drag.setMimeData(mimeData)

            drag.exec_()
Example #25
0
    def mimeData(self, indexes):
        """
        This is a single-selection model, so there should only be
        one row getting dragged.

        And what we're dragging around is simply a text version of
        the inode for the dragged file.
        :param indexes:
        :return:
        """
        mimedata = QMimeData()
        mimedata.setText(str(indexes[0].internalId()))
        return mimedata
Example #26
0
    def mimeData(self, indexes):
        # Create MimeData for drag operation
        data = QMimeData()

        # Get list of all selected file ids
        property_names = []
        for item in indexes:
            selected_row = self.itemFromIndex(item).row()
            property_names.append(self.item(selected_row, 0).data())
        data.setText(json.dumps(property_names))

        # Return Mimedata
        return data
Example #27
0
 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()
Example #28
0
    def mimeData(self, indexes):
        # Create MimeData for drag operation
        data = QMimeData()

        # Get list of all selected file ids
        files = []
        for item in indexes:
            selected_row = self.itemFromIndex(item).row()
            files.append(self.item(selected_row, 4).text())
        data.setText(json.dumps(files))
        data.setHtml("effect")

        # Return Mimedata
        return data
Example #29
0
 def mouseMoveEvent(self, event):
     if not event.buttons() and Qt.LeftButton:
         return
     distance = (event.pos() - self.start_mouse_drag).manhattanLength()
     if distance < QApplication.startDragDistance():
         return
     item = self.selectedItems()[0]
     text = "<row>" + str(item.row()) + "<row>" + "<col>" + str(item.column()) + "<col>" + "<text>" + str(item.text()) + "<text>"
     print(text)
     drag = QDrag(self)
     mim_data = QMimeData()
     mim_data.setText(text)
     drag.setMimeData(mim_data)
     dropAction = drag.exec_(Qt.MoveAction)
Example #30
0
    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
Example #31
0
 def mouseMoveEvent(self, event):
     if not (event.buttons() & Qt.LeftButton):
         return
     if (event.pos() - self.drag_start_position
         ).manhattanLength() < QApplication.startDragDistance():
         return
     if self.selectedItems():
         self.selected = self.selectedItems()
     if not self.selected:
         return
     drag = QDrag(self)
     mimedata = QMimeData()
     mimedata.setText(UNIT_EDITOR_UNIT +
                      str(self.itemWidget(self.selected[0]).card_ids))
     drag.setMimeData(mimedata)
     drag.exec_(Qt.CopyAction | Qt.MoveAction)
Example #32
0
    def mousePressEvent(self, event: QMouseEvent):
        index = self.indexAt(event.pos())
        class_name = self.model().data(index, Qt.UserRole).value()
        pixmap = self.model().data(index, Qt.DecorationRole).value()

        item_data = QByteArray()
        data_stream = QDataStream(item_data, QIODevice.WriteOnly)
        data_stream.writeQString(class_name)

        mime_data = QMimeData()
        mime_data.setData("application/x-simitemdata", item_data)

        drag = QDrag(self)
        drag.setMimeData(mime_data)
        drag.setPixmap(pixmap)
        drag.exec(Qt.MoveAction)
    def mouseMoveEvent(self, event):
        if self.tab_rect:
            self.tab_rect.moveTopLeft(event.pos())

        if event.buttons(
        ) == Qt.LeftButton and self.pressEvent and not self.bar_rect.contains(
                self.tab_rect):
            event.accept()
            index = self.currentIndex()
            mimeData = QMimeData()
            drag = QDrag(self)
            drag.setMimeData(mimeData)
            drag.setPixmap(self.pixmap)
            drag.setHotSpot(self.tab_rect.topLeft() - event.pos())
            DetachableTabWidget.drag_widget = self.parent.widget(index)
            DetachableTabWidget.drag_text = self.tabText(index)
            self.parent.removeTab(index)
            dropAction = drag.exec_(Qt.MoveAction | Qt.TargetMoveAction
                                    | Qt.IgnoreAction)
            self.parent.dragLeaveEvent(event)
            if dropAction == 0:
                self.parent.insertTab(index, DetachableTabWidget.drag_widget,
                                      DetachableTabWidget.drag_text)
                self.parent.setCurrentIndex(index)
        else:
            QTabBar.mouseMoveEvent(self, event)
Example #34
0
    def newComponentButtonMousePress(self, componentType, event):
        self.ui.build.setChecked(True)
        self.ui.wireMode.setChecked(False)
        self.ui.deleteMode.setChecked(False)
        self.ui.selectMode.setChecked(True)
        self.controller.bulbsOff()
        self.model.reRender()

        self.cursorState = CursorState.NewComponentDragging
        self.newComponentType = componentType
        self.newComponentDrag = QDrag(self)
        self.newComponentDrag.setHotSpot(
            QPoint(self.ui.circuitDiagram.blockSideLength / 2,
                   self.ui.circuitDiagram.blockSideLength / 2))
        self.newComponentDrag.setMimeData(QMimeData())
        self.newComponentDrag.setPixmap(
            QPixmap(
                self.ui.circuitDiagram.componentTypeToImageName(
                    componentType)).scaled(
                        self.ui.circuitDiagram.blockSideLength,
                        self.ui.circuitDiagram.blockSideLength))
        QApplication.setOverrideCursor(QCursor(Qt.ForbiddenCursor))
        self.newComponentDrag.exec_(Qt.MoveAction)

        self.cursorState = CursorState.Select
        self.ui.selectMode.setChecked(True)
        self.updateCursor()
 def startDrag(self, mainwin, ev):
     d = mainwin.currentDocument()
     if not d:
         return
     url = d.url()
     if url.isEmpty():
         return
     drag = QDrag(mainwin)
     data = QMimeData()
     data.setUrls([url])
     drag.setMimeData(data)
     pixmap = mainwin.style().standardPixmap(QStyle.SP_FileIcon, 0, mainwin)
     hotspot = QPoint(pixmap.width() - 5, 5)
     drag.setPixmap(pixmap)
     drag.setHotSpot(hotspot)
     drag.start(Qt.LinkAction | Qt.CopyAction)
Example #36
0
 def _get_mime_data(self, complete):
     mime_data = QMimeData()
     if complete:
         self._set_mime_data_complete(mime_data)
     else:
         self._set_mime_data_minimal(mime_data)
     return mime_data
Example #37
0
    def mimeData(self, indexes):
        mimedata = QMimeData()

        urls = []
        for idx in indexes:
            if not idx.isValid():
                continue

            nameItem = self.getNameItemFromIdx(idx)

            if nameItem:
                url = QUrl(nameItem.ipfsPath.ipfsUrl)
                urls.append(url)

        mimedata.setUrls(urls)
        return mimedata
Example #38
0
    def __export_cells_as_table(self):
        """Copy tasks and time cells as html table."""
        model = self.result_view.model()

        table_text = '<html><head>'
        table_text += '<meta http-equiv="content-type" '
        table_text += 'content="text/html; charset=utf-8">'
        table_text += '</head><body>'
        table_text += '<table cellpadding="0" cellspacing="0" border="0" '
        table_text += 'style="width:100%;">'

        table_text += '<tr>'
        table_text += ('<th style="border:2px solid black;'
                       'margin:0;padding:2px;text-align:center;'
                       'background-color:#ddd;">' + self.tr('Task') + '</th>')
        table_text += ('<th style="border:2px solid black;'
                       'margin:0;padding:2px;text-align:center;'
                       'background-color:#ddd;width:20%;">' + self.tr('Time') +
                       '</th>')
        table_text += '</tr>'

        rows = model.rowCount()
        columns_to_export = (ResultColumn.Task.value, ResultColumn.Time.value)

        for i in range(0, rows):
            table_text += '<tr>'
            for j in columns_to_export:
                content = model.data(model.index(i, j), Qt.DisplayRole)
                if j == 0:
                    table_text += ('<td style="border:2px solid black;'
                                   'margin:0;padding:2px;text-align:left;">'
                                   '{}</td>').format(content)
                else:
                    table_text += ('<td style="border:2px solid black;'
                                   'margin:0;padding:2px;text-align:center;'
                                   'width:20%;">{}</td>').format(content)
            table_text += '</tr>'

        table_text += '</tr></table></body></html>'

        clipboard = QApplication.clipboard()
        mime_data = QMimeData()
        bytes_array = QByteArray()
        bytes_array.append(table_text)
        mime_data.setData('text/html', bytes_array)

        clipboard.setMimeData(mime_data, QClipboard.Clipboard)
    def __init__(self):
        super(Demo, self).__init__()
        # 添加菜单栏、工具栏和状态栏:
        self.file_menu = self.menuBar().addMenu('File')
        self.edit_menu = self.menuBar().addMenu('Edit')
        self.help_menu = self.menuBar().addMenu("Help")

        self.file_toolbar = self.addToolBar('File')
        self.edit_toolbar = self.addToolBar('Edit')

        self.status_bar = self.statusBar()

        # 将一个动作看作一种命令,每当用户点击某个动作时,就会触发某种命令,程序从而执行相应的命令。那现在我们就要实例化几个动作
        self.new_action = QAction('New', self)
        self.open_action = QAction('OPen', self)
        self.save_action = QAction('Save', self)
        self.save_as_action = QAction('Save As', self)
        self.close_action = QAction('Close', self)
        self.cut_action = QAction('Cut', self)
        self.copy_action = QAction('Copy', self)
        self.paste_action = QAction('Paste', self)
        # 字体修改
        self.font_action = QAction('Font', self)
        # 颜色修改
        self.color_action = QAction('Color', self)
        self.about_action = QAction('Qt', self)
        self.about_author = QAction('备注', self)

        # 实例化一个QTextEdit控件
        self.text_edit = QTextEdit(self)

        # 剪切复制粘贴功能 ==> QMimeData类
        self.mime_data = QMimeData()
        self.clipboard = QApplication.clipboard()

        """
        调用QMainWindow的setCentralWidget()方法可以设置主窗口的中央控件,
        这里我们将文本编辑框text_edit设置为中央控件。调用resize()方法将窗口设置到合适的大小
        """
        self.setCentralWidget(self.text_edit)
        self.resize(450, 600)

        self.menu_init()
        self.toolbar_init()
        self.status_bar_init()
        self.action_init()
        self.text_edit_int()
Example #40
0
    def format_copy_format(self):
        """Copies the format of the selected cells to the Clipboard

        Cells are shifted so that the top left bbox corner is at 0,0

        """

        def remove_tabu_keys(attr):
            """Remove keys that are not copied from attr"""

            tabu_attrs = "merge_area", "renderer", "frozen"
            for tabu_attr in tabu_attrs:
                try:
                    attrs.pop(tabu_attr)
                except KeyError:
                    pass

        grid = self.main_window.grid
        code_array = grid.model.code_array
        cell_attributes = code_array.cell_attributes

        row, column, table = grid.current

        # Cell attributes

        new_cell_attributes = []
        selection = grid.selection

        # Format content is shifted so that the top left corner is 0,0
        (top, left), (bottom, right) = \
            selection.get_grid_bbox(grid.model.shape)

        for __selection, _, attrs in cell_attributes.for_table(table):
            new_selection = selection & __selection
            if new_selection:
                # We do not copy merged cells and cell renderers
                remove_tabu_keys(attrs)
                new_shifted_selection = new_selection.shifted(-top, -left)
                cell_attribute = new_shifted_selection.parameters, attrs
                new_cell_attributes.append(cell_attribute)

        ca_repr = bytes(repr(new_cell_attributes), encoding='utf-8')

        clipboard = QApplication.clipboard()
        mime_data = QMimeData()
        mime_data.setData("application/x-pyspread-cell-attributes", ca_repr)
        clipboard.setMimeData(mime_data)
Example #41
0
 def mouseMoveEvent(self, event):
     if not (event.buttons() & Qt.LeftButton):
         return
     if (event.pos() - self.drag_start_position
         ).manhattanLength() < QApplication.startDragDistance():
         return
     drag = QDrag(self)
     mimedata = QMimeData()
     mimedata.setText(self.text())
     drag.setMimeData(mimedata)
     pixmap = QPixmap(self.size())
     painter = QPainter(pixmap)
     painter.drawPixmap(self.rect(), self.grab())
     painter.end()
     drag.setPixmap(pixmap)
     drag.setHotSpot(event.pos())
     drag.exec_(Qt.CopyAction | Qt.MoveAction)
Example #42
0
 def startDrag(self, dropActions):
     item = self.currentItem()
     icon = item.icon()
     data = QByteArray()
     stream = QDataStream(data, QIODevice.WriteOnly)
     stream.writeQString(item.text())
     stream << icon
     mimeData = QMimeData()
     mimeData.setData("application/x-icon-and-text", data)
     drag = QDrag(self)
     drag.setMimeData(mimeData)
     pixmap = icon.pixmap(24, 24)
     drag.setHotSpot(QPoint(12, 12))
     drag.setPixmap(pixmap)
     if (drag.exec(Qt.MoveAction | Qt.CopyAction) == Qt.MoveAction):
         self.takeItem(self.row(item))
         self.update()
Example #43
0
def test_file_dd_filter_drag_enter_event(qtbot):
    widget = QLineEdit()
    qtbot.addWidget(widget)

    mime = QMimeData()
    mime.setUrls([
        QUrl("file:///path/to/file"),
    ])
    action = Qt.CopyAction | Qt.MoveAction
    point = widget.rect().center()

    event = QDragEnterEvent(point, action, mime, Qt.LeftButton, Qt.NoModifier)

    event_filter = events.FileDragAndDropFilter()
    assert event_filter.eventFilter(widget, event)

    assert event.isAccepted()
Example #44
0
    def mouseMoveEvent(self, event):
        if QLineF(event.screenPos(),
                event.buttonDownScreenPos(Qt.LeftButton)).length() < \
                        QApplication.startDragDistance():
            return

        drag = QDrag(event.widget())
        mime = QMimeData()
        drag.setMimeData(mime)

        mime.setImageData(REDDISK)
        dragImg = REDDISK.scaled(40, 40, Qt.KeepAspectRatio)
        drag.setPixmap(QPixmap.fromImage(dragImg))
        drag.setHotSpot(QPoint(dragImg.width() / 2, dragImg.height()/ 2))

        drag.exec()
        self.setCursor(Qt.OpenHandCursor)
Example #45
0
    def mouseMoveEvent(self, e: QMouseEvent):
        mime_data = QMimeData()
        self.setVisible(False)
        #self.setParent(None)
        mime_data.setData("application/hotspot",
                          b"%d %d %d" % (e.x(), e.y(), self.code))

        drag = QDrag(self)
        drag.parent = self
        # MIME 타입데이터를 Drag에 설정
        drag.setMimeData(mime_data)
        # 드래그시 위젯의 모양 유지를 위해 QPixmap에 모양을 렌더링
        pixmap = QPixmap(self.size())
        self.render(pixmap)
        drag.setPixmap(pixmap)
        drag.setHotSpot(e.pos() - self.rect().topLeft())
        drag.exec_(Qt.MoveAction)
Example #46
0
    def mouseMoveEvent(self, e: QMouseEvent):
        newBlock = self.window.addBlock(self.code, (self.x(), self.y()))
        newBlock.setParent(None)
        mime_data = QMimeData()
        mime_data.setData("application/hotspot",
                          b"%d %d %d" % (e.x(), e.y(), newBlock.code))
        drag = QDrag(newBlock)
        drag.parent = newBlock

        drag.setMimeData(mime_data)
        #newBlock.setVisible(True)
        pixmap = QPixmap(newBlock.size())
        newBlock.render(pixmap)
        drag.setPixmap(pixmap)

        drag.setHotSpot(e.pos() - newBlock.rect().topLeft())
        drag.exec_(Qt.MoveAction)
Example #47
0
    def startDrag(self, e):
        index = self.indexAt(e.pos())
        if not index.isValid():
            return

        selected = self.model().data(index, Qt.UserRole)
        selected._time = self.model().time
        # selected.file = self;

        bstream = pickle.dumps(selected)
        mimeData = QMimeData()
        mimeData.setData("application/x-DataItem", bstream)

        drag = QDrag(self)
        drag.setMimeData(mimeData)

        result = drag.exec()
Example #48
0
 def mouseMoveEvent(self, e):
     if e.buttons() != Qt.LeftButton:
         return
     mimeData = QMimeData()
     drag = QDrag(self)
     drag.setMimeData(mimeData)
     drag.setHotSpot(e.pos() - self.rect().topLeft())
     dropAction = drag.exec_(Qt.MoveAction)
Example #49
0
 def startDrag(self):
     image = self.image()
     data = QMimeData()
     data.setImageData(image)
     drag = QDrag(self)
     drag.setMimeData(data)
     if max(image.width(), image.height()) > 256:
         image = image.scaled(QSize(256, 256), Qt.KeepAspectRatio, Qt.SmoothTransformation)
     p = QPainter()
     p.begin(image)
     p.setCompositionMode(QPainter.CompositionMode_DestinationIn)
     p.fillRect(image.rect(), QColor(0, 0, 0, 160))
     p.end()
     pixmap = QPixmap.fromImage(image)
     drag.setPixmap(pixmap)
     drag.setHotSpot(pixmap.rect().center())
     drag.exec_(Qt.CopyAction)
Example #50
0
 def mimeData(self, indexes):
     """
     Public method to return the mime data.
     
     @param indexes list of indexes
     @type QModelIndexList
     @return mime data
     @rtype QMimeData
     """
     mimeData = QMimeData()
     urls = []
     for index in indexes:
         if index.isValid():
             itm = self.__manager.downloads()[index.row()]
             urls.append(QUrl.fromLocalFile(itm.absoluteFilePath()))
     mimeData.setUrls(urls)
     return mimeData
Example #51
0
 def mouseMoveEvent(self, event):
     if event.buttons() & Qt.RightButton:
         if (event.pos() - self.dragStartPosition
             ).manhattanLength() < QApplication.startDragDistance():
             return
         else:
             # Initiate "swap photos" action
             # Pass source PhotoFrameItem coordinates in json format
             drag = QDrag(event.widget())
             mimeData = QMimeData()
             mimeData.setText('{ "pos": { "x" : %f, "y" : %f }}' %
                              (event.scenePos().x(), event.scenePos().y()))
             drag.setMimeData(mimeData)
             dropAction = drag.exec_(Qt.MoveAction)
             logger.debug('dropAction=%s', str(dropAction))
     else:
         super(PhotoItem, self).mouseMoveEvent(event)
Example #52
0
 def mouseMoveEvent(self, e):  # 버튼 위에서 마우스가 움직이고 있을때 발생하는 이벤트
     # if e.buttons() != Qt.RightButton: #마우스 오른쪽 버튼이 눌린 상태가 아니면 이벤트를 종료
     if e.buttons() != Qt.LeftButton:  # 마우스 오른쪽 버튼이 눌린 상태가 아니면 이벤트를 종료
         return
     mimeData = QMimeData()  # 다양한 멀티미디어 데이터를 다룬다
     drag = QDrag(self) # 드레그 객체 생성
     drag.setMimeData(mimeData)
     drag.exec_(Qt.MoveAction)  # 객체 활성화
Example #53
0
		def mouseMoveEvent(self, event: QMouseEvent):
			if event.buttons() != Qt.RightButton:
				return

			drag = QDrag(self)

			mime_data = QMimeData()
			mime_data.setData('application/hotspot', b'%d %d' % (event.x(), event.y()))
			drag.setMimeData(mime_data)

			pixmap = QPixmap(self.size())
			self.render(pixmap)
			drag.setPixmap(pixmap)

			drag.setHotSpot(event.pos() - self.rect().topLeft())

			drag.exec_(Qt.MoveAction)
Example #54
0
 def copyAsComponent(self):
     if self.isGlyphTab():
         pass
     else:
         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)
Example #55
0
def test_EditorPane_drop_event():
    """
    If there's a drop event associated with files, cause them to be passed into
    Mu's existing file loading code.
    """
    ep = mu.interface.editor.EditorPane(None, 'baz')
    m = mock.MagicMock()
    ep.open_file = mock.MagicMock()
    ep.open_file.emit = m
    data = QMimeData()
    data.setUrls([QUrl('file://test/path.py'), QUrl('file://test/path.hex'),
                  QUrl('file://test/path.txt')])
    evt = QDropEvent(QPointF(0, 0), Qt.CopyAction, data,
                     Qt.LeftButton, Qt.NoModifier)
    ep.dropEvent(evt)
    # Upstream _load will handle invalid file type (.txt).
    assert m.call_count == 3
Example #56
0
class QtClipboardAdatper:
    UMLFRI_CLIPBOARD_FORMAT = 'application/umlfri-snippet'

    def __init__(self):
        self.__clipboard = QApplication.clipboard()
        self.__last_snippet = Application().clipboard
        self.__serialized = None

        self.__clipboard.changed.connect(self.__qt_clipboard_changed)
        Application().event_dispatcher.subscribe(
            ClipboardSnippetChangedEvent, self.__umlfri_clipboard_changed)

        self.__synchronize_from_qt()

    def __qt_clipboard_changed(self, mode):
        if mode == QClipboard.Clipboard:
            self.__synchronize_from_qt()

    def __synchronize_from_qt(self):
        mime_data = self.__clipboard.mimeData()
        if mime_data.hasFormat(self.UMLFRI_CLIPBOARD_FORMAT):
            serialized = mime_data.data(self.UMLFRI_CLIPBOARD_FORMAT).data()
            if serialized == self.__serialized:
                return False
            self.__serialized = serialized
            self.__last_snippet = Snippet.deserialize(
                serialized.decode('utf8'))

            Application().clipboard = self.__last_snippet
        else:
            Application().clipboard = None

    def __umlfri_clipboard_changed(self, event):
        if event.new_snippet is None:
            return

        if event.new_snippet is not self.__last_snippet:
            self.__last_snippet = event.new_snippet

            self.__mime_data = QMimeData()  # keep reference
            self.__serialized = event.new_snippet.serialize().encode('utf8')
            self.__mime_data.setData(self.UMLFRI_CLIPBOARD_FORMAT,
                                     self.__serialized)
            self.__clipboard.setMimeData(self.__mime_data,
                                         QClipboard.Clipboard)
Example #57
0
    def mouseMoveEvent(self, e):  ##버튼 위에서 마우스가 움직일때 발생하는 이벤트
        if e.buttons() != Qt.RightButton:
            return

        mimeData = QMimeData()  ## 다양한 멀티데이터를 다를 수 있음?

        drag = QDrag(self)
        drag.setMimeData(mimeData)
        drag.exec_(Qt.MoveAction)
Example #58
0
    def doDrag(self):
        drag = QDrag(self)
        mimeData = QMimeData()
        mimeData.setText(self.dragText)
        drag.setMimeData(mimeData)

        drag_img = QPixmap(self.width(), self.itemRowHeight)
        drag_img.fill(QColor(255, 255, 255, 100))
        painter = QPainter(drag_img)
        painter.setPen(QColor(0, 0, 0, 200))
        painter.drawText(QRectF(40, 0, self.width(), self.itemRowHeight),
                         self.dragText, QTextOption(Qt.AlignVCenter))
        painter.end()

        drag.setPixmap(drag_img)
        drag.setHotSpot(self.dragPointAtItem)
        if drag.exec(Qt.MoveAction) == Qt.MoveAction:
            print('drag')
Example #59
0
 def mousePressEvent(self, e):
     self.drop.emit({"drag": self})
     self.position = e.pos()
     mimedata = QMimeData()
     drag = QtGui.QDrag(self)
     drag.setMimeData(mimedata)
     pixmap = self.icon.pixmap(QSize(BTN_SIZE, BTN_SIZE))
     drag.setPixmap(pixmap)
     dropAction = drag.exec_(Qt.MoveAction)
Example #60
0
 def copy(self):
     widget = self.stackWidget.currentWidget()
     clipboard = QApplication.clipboard()
     mimeData = QMimeData()
     if self.isGlyphTab():
         glyph = widget.activeGlyph()
         copyGlyph = glyph.getRepresentation("TruFont.FilterSelection")
         packGlyphs = (copyGlyph, )
     else:
         glyphs = self.glyphCellView.glyphs()
         packGlyphs = (glyphs[index]
                       for index in sorted(self.glyphCellView.selection()))
     pickled = []
     for glyph in packGlyphs:
         pickled.append(glyph.serialize(blacklist=("name", "unicodes")))
     mimeData.setData("application/x-trufont-glyph-data",
                      pickle.dumps(pickled))
     clipboard.setMimeData(mimeData)