2012-05-08 40 views
2

this question非常相似,我希望能夠將圖像從PyQt應用程序拖放到OSX文件系統。從PyQt 4.x拖放到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() 

我哪裏錯了?

我知道我也需要設置被放下的媒體的名稱,所以任何指導也將不勝感激。

回答

4

你可以通過不使用圖像模仿和設置緩衝區來簡化這個過程。如果您使用的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,並命名是自動的。請享用!

+0

我會試試這個。你是一個天才,jdi。 – AteYourLembas

相關問題