开发者

PyQT: can't drag/drop plain text into browser form element, but i can back into a text editor

I've finally got a working example of both d开发者_StackOverflowragging AND dropping into & out of a listwidget, but sometimes the dragging into other contexts/applications doesn't work.

Example:

  • SUCCESS: select & drag text/plain from gedit into the listwidget and back to the text-editor
  • FAILURE: but I can't then drag the plain-text listwidgetitem into a chrome/pyqtwebview browser form element.

Goal: I'd like to have an all-purpose drag-and-drop-box for inter-application transfer: images, urls, html & text, such that the appropriate content is delivered to the dropping-upon application's capabilities.

Code:

import datetime
import cPickle
import pickle
import sys


from PyQt4 import QtGui, QtCore
from PIL import Image, ImageQt
import urllib2 as urllib

class dropZone(QtGui.QListWidget):
    def __init__(self, parent=None):
        super(dropZone, self).__init__(parent)
        self.setMinimumSize(400,480)
        self.setDragEnabled(True)
        self.setAcceptDrops(True)
        self.setIconSize(QtCore.QSize(240, 240))

    def dragEnterEvent(self, event):
        print "hello draggin!"
        print event.mimeData().text()

        if event.mimeData().hasUrls():
            event.accept()
        elif event.mimeData().hasText():
            event.accept()
        elif event.mimeData().hasImage():
            event.accept()
        else:
            event.ignore()

    def dragMoveEvent(self, event):
        if event.mimeData().hasUrls():
            event.setDropAction(QtCore.Qt.MoveAction)
            event.accept()
        elif event.mimeData().hasText():
            event.setDropAction(QtCore.Qt.MoveAction)
            event.accept()
        elif event.mimeData().hasImage():
            event.setDropAction(QtCore.Qt.MoveAction)
            event.accept()        
        else:
#            event.ignore()
            event.accept()


    def dragLeaveEvent(self, event):    #this doesn't get used unless the drag fails..
        print "bye bye dragging";
        event.accept()

    def dragAway(self,event):
         if not self.selectedIndexes(): return

         drag = QtGui.QDrag(self)
         #data = []
         md = QtCore.QMimeData()   #output setter

         for index in self.selectedIndexes():     #right now we're just doing the last one..
             if not index.isValid(): continue

         txt = self.currentItem().text()
         url = QtCore.QUrl(txt)
#         url = QtCore.QUrl().fromUserInput(txt)
#         if url.isValid():
         if url.host() != "":
             print "valid url:"+txt
             urls = [ url ]         #this is where we could have been dumping the urls in during the above loop
             md.setUrls(urls)
         elif txt != "":
             txt = self.currentItem().text()
             md.setText(txt)

         if self.currentItem().icon() != None:
             icon = self.currentItem().icon() 
             pixmap = icon.pixmap(QtCore.QSize(240, 240))
             drag.setPixmap(pixmap)     #what the user sees when dragging the object
         else:
             event.ignore()

         print "output:"+md.formats().join(', ')  #no img-data! Just urls!

         # this is important.  Without this, it won't do anything.
         drag.setMimeData(md)
         result = drag.exec_(QtCore.Qt.MoveAction)
         if result: # == QtCore.Qt.MoveAction:
            self.model().removeRow(index.row())


    def mouseMoveEvent(self, event):    #apparently the way to drag-off
        self.dragAway(event)

    def dropEvent(self, event):
        txt = event.mimeData().text()

        #need a better way to determine what to add?
        if event.mimeData().hasImage():
             qimg = event.mimeData().imageData().toPyObject()
             qimg.scaled(QtCore.QSize(240, 240), Image.ANTIALIAS)
             qpix = QtGui.QPixmap.fromImage(qimg)            #ImageQt.ImageQt(picture)
             icon = QtGui.QIcon(qpix)  #QtGui.QPixmap.fromImage(ImageQt.ImageQt(qimg))

             for url in event.mimeData().urls():
               print url.toString()
               item = QtGui.QListWidgetItem(url.toString(),self)     #os.path.basename(url)
               item.setIcon(icon)

        elif event.mimeData().hasUrls():
             for url in event.mimeData().urls():
               print url.toString()
             item = QtGui.QListWidgetItem(url.toString(),self)     #os.path.basename(url)
#             self.setText(url.toString())
             event.accept()

        elif event.mimeData().hasText():
             item = QtGui.QListWidgetItem(txt,self)     #os.path.basename(url)
             event.accept()

        else:
            event.ignore()


class testDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(testDialog, self).__init__(parent)
        self.setWindowTitle("Drag Drop Test")
        layout = QtGui.QGridLayout(self)

#        self.model = simple_model()
        self.listView = dropZone()
#        self.listView.setModel(self.model)   #preloading?
        layout.addWidget(self.listView,0,1,2,2)


if __name__ == "__main__":
    '''
    the try catch here is to ensure that the app exits cleanly no matter what
    makes life better for SPE
    '''
    try:
        app = QtGui.QApplication([])
        dl = testDialog()
        dl.exec_()
    except Exception, e:  #could use as e for python 2.6...
        print e
    sys.exit(app.closeAllWindows())


It seems to work if you replace:

result = drag.exec_(QtCore.Qt.MoveAction)

with

result = drag.exec_(QtCore.Qt.CopyAction)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜