PyQt:获取删除qlistview / qtablewidget / qlistwidget项目的路径在python app的外部

时间:2013-06-19 20:16:40

标签: python drag-and-drop pyqt pyqt4

我想创建一个PyQt应用程序,用户可以将文件拖放到listview(或类似的小部件),这些文件将被添加到列表中。这在以下示例中有效。

例如,如果用户将列表视图中的项目拖动到他们的桌面(从应用程序外部/外部),我还希望我的python程序检测/打印项目被删除的路径(例如C:\ Users \ alilly \桌面)。然后我可以编写代码将文件复制到该位置。

这是我到目前为止的部分工作代码。

导入系统     来自PyQt4.QtGui import *     来自PyQt4.QtCore import *

class MyListWidget(QListWidget):
  def __init__(self, parent):
    super(MyListWidget, self).__init__(parent)
    self.setAcceptDrops(True)
    self.setDragEnabled(True)
    self.setDragDropMode(QAbstractItemView.InternalMove)

  def mouseMoveEvent(self, event):
    self.dragObject()

  def dragEnterEvent(self, event):
    if event.mimeData().hasUrls():
      event.acceptProposedAction()
    else:
      super(MyListWidget, self).dragEnterEvent(event)

  def dragMoveEvent(self, event):
    super(MyListWidget, self).dragMoveEvent(event)

  def dropEvent(self, event):
    if event.mimeData().hasUrls():
      for url in event.mimeData().urls():
        self.addItem(url.path())
      event.acceptProposedAction()
    else:
      super(MyListWidget,self).dropEvent(event)

  def dragObject(self):
    if not self.selectedIndexes(): return

    drag = QDrag(self)

    data = []
    for index in self.selectedIndexes():
        if not index.isValid(): continue

        # this assumes your model has a nodeFromIndex() method -
        # it's easy to set one up, you'll probably have a custom
        # model class anyways
        # node = self.model().nodeFromIndex(index)
        # data.append(str(node))

    # in this case I'm just making a newline-seperated list
    # of the data, you could do pretty much anything here
    md = QMimeData()
    md.setData('text/plain', "\n".join(data))

    # this is important.  Without this, it won't do anything.
    # you can use different actions like Qt.MoveAction, which
    # would remove the item from your model, but then your model
    # has to be more complicated.  I'm only interested in copy here.
    drag.setMimeData(md)
    dropAction = drag.exec_(Qt.CopyAction)

class MyWindow(QWidget):
  def __init__(self):
    super(MyWindow,self).__init__()
    self.setGeometry(100,100,300,400)
    self.setWindowTitle("Filenames")

    self.list = MyListWidget(self)
    layout = QVBoxLayout(self)
    layout.addWidget(self.list)

    self.setLayout(layout)

if __name__ == '__main__':

  app = QApplication(sys.argv)
  app.setStyle("plastique")

  window = MyWindow()
  window.show()

  sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:2)

不确定其他平台,但在Windows上,您无需编写自己的代码来复制或移动文件。只需使用'text / uri-list'将文件路径添加到mimedata,windows就会将其复制/移动到放置位置

testFile = 'file:///C:/testFile.txt'
md = QMimeData()
md.setData('text/uri-list', QtCore.QByteArray(testFile))