PyQt:获取在python应用程序外部放置qlistview/qtablewidget/qlistwidget项的路径
我想创建一个PyQt应用程序,用户可以将文件拖放到listview(或类似的小部件)上,这些文件将被添加到列表中。在下面的示例中,这一点非常有效 例如,如果用户将一个项目从listview拖到他们的桌面(从应用程序外部/外部),我还希望我的python程序检测/打印该项目被拖放的路径(例如C:\Users\alilly\desktop)。然后我可以编写代码将文件复制到该位置 这是我到目前为止部分工作的代码 导入系统 从PyQt4.QtGui导入* 从PyQt4.QtCore导入*PyQt:获取在python应用程序外部放置qlistview/qtablewidget/qlistwidget项的路径,python,drag-and-drop,pyqt,pyqt4,Python,Drag And Drop,Pyqt,Pyqt4,我想创建一个PyQt应用程序,用户可以将文件拖放到listview(或类似的小部件)上,这些文件将被添加到列表中。在下面的示例中,这一点非常有效 例如,如果用户将一个项目从listview拖到他们的桌面(从应用程序外部/外部),我还希望我的python程序检测/打印该项目被拖放的路径(例如C:\Users\alilly\desktop)。然后我可以编写代码将文件复制到该位置 这是我到目前为止部分工作的代码 导入系统 从PyQt4.QtGui导入* 从PyQt4.QtCore导入* class M
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_())
不确定其他平台,但在Windows上,您不需要编写自己的代码来复制或移动文件。只需使用“text/uri list”将文件路径添加到mimedata,windows就会将其复制/移动到放置位置
testFile = 'file:///C:/testFile.txt'
md = QMimeData()
md.setData('text/uri-list', QtCore.QByteArray(testFile))
有趣的差不多4年后,我去了stackoverflow准备问同样的问题,结果发现我在4年前问过这个问题,但从来没有看到你的回答。刚刚测试过,效果很好。抱歉耽搁了4年。:)