PyQT:无法将纯文本拖放到浏览器表单元素中,但我可以返回文本编辑器

发布于 2024-11-02 23:51:06 字数 5109 浏览 0 评论 0原文

终于得到了一个将拖放到 & 中的工作示例。从列表小部件中删除,但有时拖动到其他上下文/应用程序中不起作用。

示例:

  • 成功:选择&将文本/纯文本从 gedit 拖入列表小部件并返回文本编辑器
  • 失败:但我无法将纯文本列表小部件拖动到 chrome/pyqtwebview 浏览器表单元素中。

目标: 我想要一个用于应用程序间传输的通用拖放框:图像、url、html 和 HTML 文件。文本,以便将适当的内容传递给掉落的应用程序的功能。

代码:

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())

I've finally got a working example of both dragging 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())

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦一生花开无言 2024-11-09 23:51:06

如果你替换:

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

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

It seems to work if you replace:

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

with

result = drag.exec_(QtCore.Qt.CopyAction)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文