【问题标题】:Drag and drop from PyQt 4.x to OSX file system从 PyQt 4.x 拖放到 OSX 文件系统
【发布时间】:2012-05-08 18:32:44
【问题描述】:

this question 非常相似,我希望能够将图像从 PyQt 应用程序拖放到 OSX 文件系统。

但是,当我使用以下代码时,放置位置没有出现任何内容。

看来我很接近了。如果我将mimeData.setData(mimeType, byteArray) 更改为mimeData.setData("text/plain", selectedImagePath),我会在放置目标处得到一个“无标题剪辑”文件,所以至少我可以确定拖放操作正在工作。

def startDrag(self, event):     

    selectedImagePath = "/sample/specified/file.jpg"


    ## convert to  a bytestream
    #
    mimeData = QtCore.QMimeData()
    image = QtGui.QImage(selectedImagePath)
    extension = os.path.splitext(selectedImagePath)[1].strip(".")
    mimeType = "image/jpeg" if extension in ["jpeg", "jpg"] else "image/png"

    byteArray = QtCore.QByteArray()
    bufferTime = QtCore.QBuffer(byteArray)
    bufferTime.open(QtCore.QIODevice.WriteOnly)
    image.save(bufferTime, extension.upper())

    mimeData.setData(mimeType, selectedImagePath)

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

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

    event.accept()  

我哪里出错了?

我意识到我还需要设置已删除媒体的名称,因此也将不胜感激任何有关此方面的指导。

【问题讨论】:

    标签: drag-and-drop qt4 pyqt osx-snow-leopard


    【解决方案1】:

    您可以通过不使用图像 mimetypes 和设置缓冲区来简化此过程。如果你使用 url,这将是一种更通用的方法......

    自定义 QLabel 的示例:

    class Label(QtGui.QLabel):
    
        ...
    
        def mousePressEvent(self, event): 
    
            event.accept()
    
            selectedImagePath = "/Users/justin/Downloads/smile.png"
    
            # a pixmap from the label, or could be a custom
            # one to represent the drag preview 
            pixmap = self.pixmap()
    
            # make sure the thumbnail isn't too big during the drag
            if pixmap.width() > 320 or pixmap.height() > 640:
                    pixmap = pixmap.scaledToWidth(128)
    
            mimeData = QtCore.QMimeData()
            mimeData.setUrls([QtCore.QUrl(selectedImagePath)])
    
            drag = QtGui.QDrag(self)
            drag.setMimeData(mimeData)
            drag.setPixmap(pixmap)
            # center the hotspot image over the mouse click pos
            drag.setHotSpot(QtCore.QPoint(
                pixmap.width() / 2, 
                pixmap.height() / 2))
    
            dropAction = drag.exec_(QtCore.Qt.CopyAction, QtCore.Qt.CopyAction)
    

    现在桌面只会解释 url,命名是自动的。尽情享受吧!

    【讨论】:

    • 我试试看。你是个天才,jdi。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    相关资源
    最近更新 更多