How to Drag and Drop from ListWidget onto ComboBox - python

The goal is to be able to drag-and-drop ListWidget items onto the comboBox. The dropped items should be added to the combobox. Ideally we want to avoid any tricks with reading listWidget's .currentItem() or .selectedItems() and etc... Ideas?
from PyQt4 import QtGui, QtCore
import sys, os
class MyClass(object):
def __init__(self):
super(MyClass, self).__init__()
self.name=None
def setName(self, arg):
self.name=arg
def getName(self):
return self.name
class DropableComboBox(QtGui.QComboBox):
def __init__(self):
self.model_mime_type = 'application/x-qabstractitemmodeldatalist'
super(DropableComboBox, self).__init__()
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasFormat(self.model_mime_type) or event.mimeData().hasFormat('text/plain'):
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
else:
super(DropableComboBox, self).dropEvent(event)
self.emit(QtCore.SIGNAL("dropped"))
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.listWidget = QtGui.QListWidget()
self.listWidget.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
self.listWidget.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.listWidget.currentItemChanged.connect(self.item_clicked)
for i in range(3):
my_item=QtGui.QListWidgetItem()
name='ListWidget Item '+str(i)
my_item.setText(name)
self.listWidget.addItem(my_item)
myObject=MyClass()
myObject.setName(name)
my_item.setData(QtCore.Qt.UserRole, myObject)
myBoxLayout.addWidget(self.listWidget)
self.ComboBox = DropableComboBox()
for i in range(3):
self.ComboBox.addItem("Combobox Item " + str(i))
self.ComboBox.currentIndexChanged.connect(self.combobox_selected)
self.connect(self.ComboBox, QtCore.SIGNAL("dropped"), self.droppedOnCombobox)
myBoxLayout.addWidget(self.ComboBox)
def item_clicked(self, arg=None):
print arg.data(QtCore.Qt.UserRole).toPyObject().getName()
def combobox_selected(self, index):
myObject=self.ComboBox.itemData(index).toPyObject()
if hasattr(myObject, 'getName'): print myObject.getName()
def droppedOnCombobox(self):
print "Drop!"
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())

The "proper" way to do this would be to unpack the mimedata using a QDataStream. However, this would seem to require the use of a QMap, which is not available in PyQt. So instead, it can be done in a slightly hacky (or should that be "tricky"?) way by getting a proxy model to the dirty work for us:
class DropableComboBox(QtGui.QComboBox):
def __init__(self):
super(DropableComboBox, self).__init__()
self.model_mime_type = 'application/x-qabstractitemmodeldatalist'
self.setAcceptDrops(True)
self._proxymodel = QtGui.QStandardItemModel(self)
def dropEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
elif event.mimeData().hasFormat(self.model_mime_type):
self._proxymodel.setRowCount(0)
self._proxymodel.dropMimeData(
event.mimeData(), QtCore.Qt.CopyAction,
0, 0, QtCore.QModelIndex())
for index in range(self._proxymodel.rowCount()):
item = self._proxymodel.item(index, 0)
self.addItem(item.text())
# no point calling the base-class dropEvent here,
# because it's a NO-OP in QComboBox
self.emit(QtCore.SIGNAL("dropped"))
NB:
This will copy the items from the list-widget, rather than moving them (which you didn't ask for). Also, if you want to prevent duplicates being added, use setDuplicatesEnabled. And if you want to alter how the items are added, use setInsertPolicy.

Related

pyqt5 override dropEvent python

I am trying to add drag and drop functionality to a small application. Getting data from a QlistWidget and Dropping the data on a QTableWidget. I should override the dropEvent of QTableWidget in order to add some other functions when dropping the data. But i have trouble, i think i can not get the text() of the object gotten from the ListWidget. here is the code:
class Table(QtWidgets.QTableWidget):
def __init__(self,r,c, parent=None):
super().__init__(r,c,parent)
self.init_ui()
def init_ui(self):
self.setAcceptDrops(True)
self.setDragDropMode(QtWidgets.QAbstractItemView.DragDrop)
"""def dragMoveEvent(self, e):
e.setDropAction(QtCore.Qt.MoveAction)
e.accept()
def dragEnterEvent(self,e):
e.accept()"""
def dropEvent(self,e):
data = e.mimeData()
a=e.pos()
row = self.rowAt(a.y())
col = self.columnAt(a.x())
self.setItem(row,col,QtWidgets.QTableWidgetItem(data.text()))
print(row,col)
print(type(data.text()))
print(e.source())
x = data.text()
print(x)
e.accept()
`
The data that is transmitted from a QListWidget through the drag-and-drop is not given through text(), because an item has much more information identified by the roles, in addition you can drag several items. The data is transmitted using the MIME type application/x-qabstractitemmodeldatalist and the solution is to decode it as shown below:
from PyQt5 import QtCore, QtWidgets
class TableWidget(QtWidgets.QTableWidget):
def __init__(self, r,c, parent=None):
super(TableWidget, self).__init__(r,c, parent)
self.setAcceptDrops(True)
self.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly)
def dropEvent(self, event):
md = event.mimeData()
fmt = "application/x-qabstractitemmodeldatalist"
if md.hasFormat(fmt):
encoded = md.data(fmt)
stream = QtCore.QDataStream(encoded, QtCore.QIODevice.ReadOnly)
table_items = []
while not stream.atEnd():
# row and column where it comes from
row = stream.readInt32()
column = stream.readInt32()
map_items = stream.readInt32()
it = QtWidgets.QTableWidgetItem()
for i in range(map_items):
role = stream.readInt32()
value = QtCore.QVariant()
stream >> value
it.setData(role, value)
table_items.append(it)
for it in table_items:
print(it, it.text())
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
list_widget = QtWidgets.QListWidget()
list_widget.setAcceptDrops(False)
list_widget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
list_widget.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly)
for i in range(10):
it = QtWidgets.QListWidgetItem("item-{}".format(i))
list_widget.addItem(it)
table_widget = TableWidget(5, 10)
central_widget = QtWidgets.QWidget()
hlay = QtWidgets.QHBoxLayout(central_widget)
hlay.addWidget(list_widget)
hlay.addWidget(table_widget)
self.setCentralWidget(central_widget)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

PyQt5 draggable icons from a listview to another

I struggle to drag and drop icons from a listview (ViewMode set to IconMode) to another. It's similar to what I've found in the docs.
Scenario: A user drags the QIcon 1 from ListView 1 and drops it to ListView 2. ListView 2 should add QIcon 1 to its model. Moreover I want to do some background work when a specific QIcon is added to ListView 2. How do I know that QIcon 1 was dropped to ListView 2 and not QIcon 2?
mainwindow (sets up the layout, loads the images into listview 1):
class Ui_MainWindow(object):
...
def loadImages(self):
model = QStandardItemModel()
images = Path("images").glob("*.*")
for image in images:
item = QStandardItem()
item.setIcon(QIcon(str(image)))
model.appendRow(item)
self.listView1.setModel(model)
listview 1:
class ListView1(QListView):
def __init__(self):
super().__init__()
self.setAcceptDrops(False)
self.setViewMode(QtWidgets.QListView.IconMode)
self.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.setIconSize(QSize(50, 50))
self.setResizeMode(QtWidgets.QListView.Adjust)
self.setDragDropMode(QAbstractItemView.DragOnly)
listview 2:
class ListView2(QListView):
def __init__(self):
super().__init__()
self.setViewMode(QtWidgets.QListView.IconMode)
self.setDragDropMode(QAbstractItemView.DropOnly)
self.setIconSize(QSize(50, 50))
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
event.accept()
def dragMoveEvent(self, event):
event.accept()
def dropEvent(self, event):
event.accept()
event.setDropAction(QtCore.Qt.MoveAction)
event.acceptProposedAction()
How can I drag and drop an icon from listview 1 to listview 2 and access its properties?
It is not necessary to overwrite dragEnterEvent, dragMoveEvent or dropEvent since those implementations already exist and work correctly, the example you point out is for other types of widgets that do not have those events implemented.
from pathlib import Path
from PyQt5 import QtCore, QtGui, QtWidgets
class LListView(QtWidgets.QListView):
def __init__(self, parent=None):
super(LListView, self).__init__(parent)
self.model = QtGui.QStandardItemModel(self)
self.setModel(self.model)
self.setAcceptDrops(False)
self.setViewMode(QtWidgets.QListView.IconMode)
self.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.setIconSize(QtCore.QSize(50, 50))
self.setResizeMode(QtWidgets.QListView.Adjust)
self.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly)
class RListView(QtWidgets.QListView):
def __init__(self, parent=None):
super(RListView, self).__init__(parent)
self.model = QtGui.QStandardItemModel(self)
self.setModel(self.model)
self.setAcceptDrops(True)
self.setViewMode(QtWidgets.QListView.IconMode)
self.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.setIconSize(QtCore.QSize(50, 50))
self.setResizeMode(QtWidgets.QListView.Adjust)
self.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
central_widget = QtWidgets.QWidget()
self.l_view = LListView()
self.r_view = RListView()
self.setCentralWidget(central_widget)
lay = QtWidgets.QHBoxLayout(central_widget)
lay.addWidget(self.l_view)
lay.addWidget(self.r_view)
self.loadImages()
def loadImages(self):
images = Path("images").glob("*.*")
for image in images:
item = QtGui.QStandardItem()
item.setIcon(QtGui.QIcon(str(image)))
self.l_view.model.appendRow(item)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
Update:
If you want to add an identifier this can be done through a role that you pass when creating the item, and then in the dropEvent() get all the roles, then get the role you want and through it the identifier:
from pathlib import Path
from PyQt5 import QtCore, QtGui, QtWidgets
class LListView(QtWidgets.QListView):
def __init__(self, parent=None):
super(LListView, self).__init__(parent)
self.m_model = QtGui.QStandardItemModel(self)
self.setModel(self.m_model)
self.setAcceptDrops(False)
self.setViewMode(QtWidgets.QListView.IconMode)
self.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.setIconSize(QtCore.QSize(50, 50))
self.setResizeMode(QtWidgets.QListView.Adjust)
self.setDragDropMode(QtWidgets.QAbstractItemView.DragOnly)
class RListView(QtWidgets.QListView):
def __init__(self, parent=None):
super(RListView, self).__init__(parent)
self.m_model = QtGui.QStandardItemModel(self)
self.setModel(self.m_model)
self.setAcceptDrops(True)
self.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.setIconSize(QtCore.QSize(50, 50))
self.setResizeMode(QtWidgets.QListView.Adjust)
self.setDragDropMode(QtWidgets.QAbstractItemView.DropOnly)
def dropEvent(self, event):
last_row_count = self.model().rowCount()
super(RListView, self).dropEvent(event)
# check if an item is added
if self.model().rowCount() > last_row_count:
md = event.mimeData()
fmt = "application/x-qabstractitemmodeldatalist"
if md.hasFormat(fmt):
encoded = md.data(fmt)
stream = QtCore.QDataStream(encoded, QtCore.QIODevice.ReadOnly)
datas = []
item = {}
while not stream.atEnd():
row = stream.readInt32()
column = stream.readInt32()
map_items = stream.readInt32()
for i in range(map_items):
key = stream.readInt32()
value = QtCore.QVariant()
stream >> value
item[QtCore.Qt.ItemDataRole(key)] = value
datas.append(item)
for data in datas:
identifier = data[QtCore.Qt.UserRole+1].value()
print("identifier: ", identifier)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
central_widget = QtWidgets.QWidget()
self.l_view = LListView()
self.r_view = RListView()
self.setCentralWidget(central_widget)
lay = QtWidgets.QHBoxLayout(central_widget)
lay.addWidget(self.l_view)
lay.addWidget(self.r_view)
self.loadImages()
def loadImages(self):
images = Path("images").glob("*.*")
for i, image in enumerate(images):
item = QtGui.QStandardItem()
identifier = "img_{:06d}".format(i+1)
item.setData(identifier, QtCore.Qt.UserRole+1)
item.setIcon(QtGui.QIcon(str(image)))
self.l_view.m_model.appendRow(item)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())

PyQt - object has no attribute 'connect'

I am using PyQt5, and I want to make a Drag&Drop system.
I got the code on this post : PyQT4: Drag and drop files into QListWidget
When I Run, I got the following error : AttributeError: 'MainForm' object has no attribute 'connect'
The code:
import sys
import os
from PyQt5.Qt import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class TestListView(QListWidget):
def __init__(self, type, parent=None):
super(TestListView, self).__init__(parent)
self.setAcceptDrops(True)
self.setIconSize(QSize(72, 72))
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(Qt.CopyAction)
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(Qt.SIGNAL("dropped"), links)
else:
event.ignore()
class MainForm(QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
self.view = TestListView(self)
self.connect(self.view, Qt.SIGNAL("dropped"), self.pictureDropped)
self.setCentralWidget(self.view)
def pictureDropped(self, l):
for url in l:
if os.path.exists(url):
print(url)
icon = QIcon(url)
pixmap = icon.pixmap(72, 72)
icon = QIcon(pixmap)
item = QListWidgetItem(url, self.view)
item.setIcon(icon)
item.setStatusTip(url)
def main():
app = QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()
if __name__ == '__main__':
main()
The problem is that you are using an old form of connection, you must update the following things:
create the signal:
class TestListView(QListWidget):
dropped = pyqtSignal(list)
Also change:
self.emit(Qt.SIGNAL("dropped"), links)
to:
self.dropped.emit(links)
And change:
self.connect(self.view, Qt.SIGNAL("dropped"), self.pictureDropped)
to:
self.view.dropped.connect(self.pictureDropped)
For more information you can read here
Complete code:
import sys
import os
from PyQt5.Qt import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class TestListView(QListWidget):
dropped = pyqtSignal(list)
def __init__(self, type, parent=None):
super(TestListView, self).__init__(parent)
self.setAcceptDrops(True)
self.setIconSize(QSize(72, 72))
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(Qt.CopyAction)
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.dropped.emit(links)
else:
event.ignore()
class MainForm(QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
self.view = TestListView(self)
self.view.dropped.connect(self.pictureDropped)
self.setCentralWidget(self.view)
def pictureDropped(self, l):
for url in l:
if os.path.exists(url):
print(url)
icon = QIcon(url)
pixmap = icon.pixmap(72, 72)
icon = QIcon(pixmap)
item = QListWidgetItem(url, self.view)
item.setIcon(icon)
item.setStatusTip(url)
def main():
app = QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()
if __name__ == '__main__':
main()

PyQt: How to get listItem Index after ListView's onDrop()

This example creates a simple dialog window with two drag-and-drop enabled listWidgets (thanks ekhumoro!).
On dropEvent the droppedOnA() and droppedOnB() functions print out an information: what listWidgets the items came from and what indexes they used to have. But I need to find what indexes the dropped listItems assigned after they were dropped onto a QListWidget-receiver. I would appreciate if it would be explained how to achieve this.
from PyQt4 import QtGui, QtCore
import sys, os
class MyClass(object):
def __init__(self):
super(MyClass, self).__init__()
class ThumbListWidget(QtGui.QListWidget):
_drag_info = []
def __init__(self, type, name, parent=None):
super(ThumbListWidget, self).__init__(parent)
self.setObjectName(name)
self.setIconSize(QtCore.QSize(124, 124))
self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setAcceptDrops(True)
def startDrag(self, actions):
self._drag_info[:] = [str(self.objectName())]
for item in self.selectedItems():
self._drag_info.append(self.row(item))
super(ThumbListWidget, self).startDrag(actions)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
super(ThumbListWidget, self).dragEnterEvent(event)
def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
super(ThumbListWidget, self).dragMoveEvent(event)
def dropEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
else:
# event.setDropAction(QtCore.Qt.MoveAction)
super(ThumbListWidget, self).dropEvent(event)
self.emit(QtCore.SIGNAL("dropped"), self._drag_info )
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
self.listItems={}
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.listWidgetA = ThumbListWidget(self, 'MainTree')
self.listWidgetB = ThumbListWidget(self, 'SecondaryTree')
for i in range(7):
listItemA=QtGui.QListWidgetItem()
listItemA.setText('A'+'%04d'%i)
self.listWidgetA.addItem(listItemA)
myClassInstA=MyClass()
listItemA.setData(QtCore.Qt.UserRole, myClassInstA)
listItemB=QtGui.QListWidgetItem()
listItemB.setText('A'+'%04d'%i)
self.listWidgetB.addItem(listItemB)
myClassInstB=MyClass()
listItemB.setData(QtCore.Qt.UserRole, myClassInstB)
myBoxLayout.addWidget(self.listWidgetA)
myBoxLayout.addWidget(self.listWidgetB)
self.connect(self.listWidgetA, QtCore.SIGNAL("dropped"), self.droppedOnA)
self.connect(self.listWidgetB, QtCore.SIGNAL("dropped"), self.droppedOnB)
def droppedOnA(self, dropped_list):
print '\n\t dropped On MainTree', dropped_list,
def droppedOnB(self, dropped_list):
print '\n\t dropped On SecondaryTree', dropped_list
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(720,480)
sys.exit(app.exec_())
Not tested to destruction, but try reimplementing rowsInserted and emitting the draginfo from there:
class ThumbListWidget(QtGui.QListWidget):
_drag_info = []
def __init__(self, type, name, parent=None):
...
self._dropping = False
def dropEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
else:
# event.setDropAction(QtCore.Qt.MoveAction)
self._dropping = True
super(ThumbListWidget, self).dropEvent(event)
self._dropping = False
def rowsInserted(self, parent, start, end):
if self._dropping:
self._drag_info.append((start, end))
self.emit(QtCore.SIGNAL("dropped"), self._drag_info)
super(ThumbListWidget, self).rowsInserted(parent, start, end)

How to Drag and Drop from One QListWidget to Another

There are two QListWIdgets sitting in a same dialog window. The DragDrop functionality has been enabled for both. If I drag and drop a file to any of two ListWidges the program recognizes it and prints out the list of the files dropped. But aside from drag and dropping files I would like to be able to drag and drop the List widget Items from one to another. If I drag the ListItems the drag and drop event is triggered. But it is not able to recognize what Items were dropped onto the widget. The example code is below. The goal is to drag-drop the list items from one ListWidget to another.
import sys, os
from PyQt4 import QtCore, QtGui
class ThumbListWidget(QtGui.QListWidget):
def __init__(self, type, parent=None):
super(ThumbListWidget, self).__init__(parent)
self.setAcceptDrops(True)
self.setIconSize(QtCore.QSize(124, 124))
def dragEnterEvent(self, event):
if event.mimeData().hasUrls:
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
event.ignore()
def dropEvent(self, event):
if event.mimeData().hasUrls:
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
else:
event.ignore()
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
self.listItems={}
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.listWidgetA = ThumbListWidget(self)
for i in range(12):
QtGui.QListWidgetItem( 'Item '+str(i), self.listWidgetA )
myBoxLayout.addWidget(self.listWidgetA)
self.listWidgetB = ThumbListWidget(self)
myBoxLayout.addWidget(self.listWidgetB)
self.listWidgetA.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
self.listWidgetA.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.connect(self.listWidgetA, QtCore.SIGNAL("dropped"), self.items_dropped)
self.listWidgetA.currentItemChanged.connect(self.item_clicked)
self.listWidgetB.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
self.listWidgetB.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.connect(self.listWidgetB, QtCore.SIGNAL("dropped"), self.items_dropped)
self.listWidgetB.currentItemChanged.connect(self.item_clicked)
def items_dropped(self, arg):
print arg
def item_clicked(self, arg):
print arg
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())
EDIT # 2
Here is the code that does it all. But there is no way to track down what object was dropped. The droppedOnA() and droppedOnB() methods are still not working.
from PyQt4 import QtGui, QtCore
import sys, os
class MyClassItem(QtGui.QListWidgetItem):
def __init__(self, parent=None):
super(QtGui.QListWidgetItem, self).__init__(parent)
class ThumbListWidget(QtGui.QListWidget):
def __init__(self, type, parent=None):
super(ThumbListWidget, self).__init__(parent)
self.setIconSize(QtCore.QSize(124, 124))
self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
super(ThumbListWidget, self).dragEnterEvent(event)
def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
super(ThumbListWidget, self).dragMoveEvent(event)
def dropEvent(self, event):
print 'dropEvent', event
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
else:
event.setDropAction(QtCore.Qt.MoveAction)
super(ThumbListWidget, self).dropEvent(event)
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
self.listItems={}
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.listWidgetA = ThumbListWidget(self)
self.listWidgetB = ThumbListWidget(self)
for i in range(7):
listItemAInstance=MyClassItem()
listItemAInstance.setText('A'+'%04d'%i)
listItemAInstance.setBackgroundColor(QtCore.Qt.darkGray)
if i%2: listItemAInstance.setBackgroundColor(QtCore.Qt.gray)
self.listWidgetA.addItem(listItemAInstance)
listItemBInstance=MyClassItem()
listItemBInstance.setText('B'+'%04d'%i)
if i%2: listItemBInstance.setBackgroundColor(QtCore.Qt.lightGray)
self.listWidgetB.addItem(listItemBInstance)
myBoxLayout.addWidget(self.listWidgetA)
myBoxLayout.addWidget(self.listWidgetB)
self.connect(self.listWidgetA, QtCore.SIGNAL("dropped"), self.droppedOnA)
self.connect(self.listWidgetB, QtCore.SIGNAL("dropped"), self.droppedOnB)
def droppedOnA(self, arg):
print '\n\t droppedOnA', arg.text
def droppedOnB(self, arg):
print '\n\t droppedOnB', arg.text
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())
EDIT # 3
Here is another attempt this time using MIME to pass dropped Item's objects to ListWidget. Unfortunately cPickle refuses to accept binary objects throwing a
TypeError: the sip.wrapper type cannot be instantiated or sub-classed
To get around it I convert each object names to string and use it with self.listItems={} dictionary as its key to retrieve list Item's binary objects. Which seems to be working well. But at the end when I almost though it as all done, a ListWidget with no visible errors doesn't add the dropped list Item to itself... It's strange.
self.listWidgetB.addItem(droppedItemInstance)
.
from PyQt4 import QtGui, QtCore
import sys, os
import cPickle
class MyClassItem(QtGui.QListWidgetItem):
def __init__(self, parent=None):
super(QtGui.QListWidgetItem, self).__init__(parent)
class ThumbListWidget(QtGui.QListWidget):
def __init__(self, type, parent=None):
super(ThumbListWidget, self).__init__(parent)
self.setIconSize(QtCore.QSize(124, 124))
self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
super(ThumbListWidget, self).dragEnterEvent(event)
def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
super(ThumbListWidget, self).dragMoveEvent(event)
def dropEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
else:
event.setDropAction(QtCore.Qt.MoveAction)
super(ThumbListWidget, self).dropEvent(event)
def mimeTypes(self):
return ['bstream', 'text/xml']
def mimeData(self, droppedItems):
mimedata = QtCore.QMimeData()
droppedItemsAsStrings=[]
for each in droppedItems:
droppedItemsAsStrings.append( str(each) )
bstream = cPickle.dumps(droppedItemsAsStrings)
mimedata.setData('bstream', bstream)
return mimedata
def dropMimeData(self, action, mimedata, row):
if action == QtCore.Qt.IgnoreAction: return True
dropped=cPickle.loads(str(mimedata.data('bstream')))
self.emit(QtCore.SIGNAL("dropped"), dropped)
return True
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
self.listItems={}
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.listWidgetA = ThumbListWidget(self)
self.listWidgetB = ThumbListWidget(self)
for i in range(7):
listItemAInstance=MyClassItem()
listItemAInstance.setText('A'+'%04d'%i)
listItemAInstance.setBackgroundColor(QtCore.Qt.darkGray)
if i%2: listItemAInstance.setBackgroundColor(QtCore.Qt.gray)
self.listWidgetA.addItem(listItemAInstance)
listItemBInstance=MyClassItem()
listItemBInstance.setText('B'+'%04d'%i)
if i%2: listItemBInstance.setBackgroundColor(QtCore.Qt.lightGray)
self.listWidgetB.addItem(listItemBInstance)
self.listItems[str(listItemAInstance)]=listItemAInstance
self.listItems[str(listItemBInstance)]=listItemBInstance
myBoxLayout.addWidget(self.listWidgetA)
myBoxLayout.addWidget(self.listWidgetB)
self.connect(self.listWidgetA, QtCore.SIGNAL("dropped"), self.droppedOnA)
self.connect(self.listWidgetB, QtCore.SIGNAL("dropped"), self.droppedOnB)
def droppedOnA(self, droppedItemsAsStrings):
print '\n\t droppedOnA()'
for each in droppedItemsAsStrings:
if each in self.listItems.keys():
droppedItemInstance = self.listItems[each]
print 'adding', droppedItemInstance.text()
self.listWidgetA.addItem(droppedItemInstance)
def droppedOnB(self, droppedItemsAsStrings):
print '\n\t droppedOnB()'
for each in droppedItemsAsStrings:
if each in self.listItems.keys():
droppedItemInstance = self.listItems[each]
self.listWidgetB.addItem(droppedItemInstance)
print 'adding', droppedItemInstance.text()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())
Here is a revised code. It is working like a charm! Bravo!
from PyQt4 import QtGui, QtCore
import sys, os
class ThumbListWidget(QtGui.QListWidget):
def __init__(self, type, parent=None):
super(ThumbListWidget, self).__init__(parent)
self.setIconSize(QtCore.QSize(124, 124))
self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
super(ThumbListWidget, self).dragEnterEvent(event)
def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
super(ThumbListWidget, self).dragMoveEvent(event)
def dropEvent(self, event):
print 'dropEvent', event
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
else:
event.setDropAction(QtCore.Qt.MoveAction)
super(ThumbListWidget, self).dropEvent(event)
class Dialog_01(QtGui.QMainWindow):
def __init__(self):
super(QtGui.QMainWindow,self).__init__()
self.listItems={}
myQWidget = QtGui.QWidget()
myBoxLayout = QtGui.QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.listWidgetA = ThumbListWidget(self)
for i in range(12):
QtGui.QListWidgetItem( 'Item '+str(i), self.listWidgetA )
myBoxLayout.addWidget(self.listWidgetA)
self.listWidgetB = ThumbListWidget(self)
myBoxLayout.addWidget(self.listWidgetB)
self.connect(self.listWidgetA, QtCore.SIGNAL("dropped"), self.items_dropped)
self.listWidgetA.currentItemChanged.connect(self.item_clicked)
self.connect(self.listWidgetB, QtCore.SIGNAL("dropped"), self.items_dropped)
self.listWidgetB.currentItemChanged.connect(self.item_clicked)
def items_dropped(self, arg):
print 'items_dropped', arg
def item_clicked(self, arg):
print arg
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(480,320)
sys.exit(app.exec_())
Assuming you want to move the list-widget items, your subclass should be as below (note that setDragDropMode and setSelectionMode have been moved into __init__):
class ThumbListWidget(QtGui.QListWidget):
def __init__(self, type, parent=None):
super(ThumbListWidget, self).__init__(parent)
self.setIconSize(QtCore.QSize(124, 124))
self.setDragDropMode(QtGui.QAbstractItemView.DragDrop)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
else:
super(ThumbListWidget, self).dragEnterEvent(event)
def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
else:
super(ThumbListWidget, self).dragMoveEvent(event)
def dropEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
links = []
for url in event.mimeData().urls():
links.append(str(url.toLocalFile()))
self.emit(QtCore.SIGNAL("dropped"), links)
else:
event.setDropAction(QtCore.Qt.MoveAction)
super(ThumbListWidget, self).dropEvent(event)
The above code did not work for me, when implementing the Python 3 style of super().
The issue is that the inherited methods dragMoveEvent and dragDropEvent were not being overwritten with the new definitions in the child class.
Therefore event.setDropAction(QtCore.Qt.MoveAction) was not being called, and the widget behavior defaulted to QtCore.Qt.CopyAction.
I solved this using the setDefaultDropAction() method inherited from the QAbstractItemView class.
Here is the implementation in PyQt5 and Python 3.7:
class NewDragDropWidget(QListWidget):
def __init__(self):
super().__init__()
self.setIconSize(QtCore.QSize(124, 124))
self.setDragDropMode(QAbstractItemView.DragDrop)
self.setDefaultDropAction(QtCore.Qt.MoveAction) # this was the magic line
self.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.setAcceptDrops(True)

Categories