Issues with QMimeData.text()

Vincent Vande Vyvre vincent.vande.vyvre at telenet.be
Sat Jun 13 08:11:30 BST 2020


Le 13/06/20 à 02:39, Bryce Beagle a écrit :
> Hi,
>
> I'm trying to implement drag-and-drop behavior in my widget and I'm
> having issues with the QMimeData that is provided in the QDropEvent. 
>
> When dragging text from some applications (e.g. PyCharm),
> event.mimeData().text() always returns an empty string. If I manually
> use event.mimeData().data('text/plain'), I get my text just fine,
> albeit as a bytes object. 
>
> The Qt documentation for QMimeData::text() says that it "Returns a
> plain text (MIME type text/plain) representation of the data.", so I
> feel that if the 'text/plain' format is defined, this should work
> fine. For reference, dragging from PyCharm, event.mimeData().formats
> returns:
>
> ['text/plain', 'text/plain;charset=UTF-16',
> 'text/plain;charset=UTF-8', 'text/plain;charset=UTF-16BE',
> 'text/plain;charset=UTF-16LE', 'text/plain;charset=ISO-8859-1',
> 'text/plain;charset=US-ASCII', 'text/plain;charset=unicode']
>
> Here's an MCVE using PyQt 5.15.0
>
> from PyQt5.QtGui import QDragEnterEvent, QDragMoveEvent, QDropEvent
> from PyQt5.QtWidgets import QApplication, QTextEdit
>
>
> class DragTextEdit(QTextEdit):
>
>     def dragEnterEvent(self, event: QDragEnterEvent):
>         event.acceptProposedAction()
>
>     def dragMoveEvent(self, event: QDragMoveEvent):
>         event.acceptProposedAction()
>
>     def dropEvent(self, event: QDropEvent):
>         data = event.mimeData()
>         print("data.text():", data.text())  # Empty string
>         print("data.data('text/plain'):", data.data('text/plain'))  #
> bytes
>
>
> app = QApplication([])
> text_edit = DragTextEdit()
> text_edit.show()
> app.exec_()

Hi,

I've changed your code:

    def dropEvent(self, event: QDropEvent):
        data = event.mimeData()
        print("data.text():", data.text(), type(data.text()))
        print("data.data('text/plain'):", str(data.data('text/plain')),
               type(data.data('text/plain')))

And the result:

data.text(): Déjà-vu <class 'str'>
data.data('text/plain'): b'D\xc3\xa9j\xc3\xa0-vu' <class
'PyQt5.QtCore.QByteArray'>

On Ubuntu Mate, the text "Déjà-vu" is dragged from Pluma (old Gedit)

Vincent

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.riverbankcomputing.com/pipermail/pyqt/attachments/20200613/93c0bc0d/attachment.htm>


More information about the PyQt mailing list