PySide2: How to keep QTreeWidgetItem widgets? - python

I have a problem with my custom QTreeWidget losing the associated widgets for each QTreeWidgetItem when it gets dragged and dropped. I understand that this is due to the item being destroyed and re-created at it's new position, and that it has something to do with the QMimeType, I believe? But I'm not sure how to work around this to get it to work and preserve/re-create these widgets? Could I possibly un-parent & reparent them, somehow? The examples I've been able to find have largely been in QT, which I can read, but I'm not really sure how to implement a solution in PySide2/PyQt. Would anybody be able to give me any pointers?
My code is written for Maya, but hopefully it should be able to work outside of Maya as well. (The custom dropEvent is needed due to a Maya/Mac bug that causes drag and drop actions to completely remove the item on drop.) You can see that item5 has been re-ordered, but lost it's associated button.
import sys
from PySide2 import QtCore, QtWidgets
def main():
try:
app = QtWidgets.QApplication(sys.argv)
ui = TreeUI()
ui.show()
app.exec_()
except RuntimeError:
from maya import OpenMayaUI as omui
try:
import shiboken2 as shiboken
except ImportError:
import shiboken
pointer = omui.MQtUtil.mainWindow()
win = shiboken.wrapInstance(long(pointer), QtWidgets.QWidget)
ui = TreeUI(parent=win)
ui.show()
class Tree(QtWidgets.QTreeWidget):
def __init__(self, parent=None):
super(Tree, self).__init__(parent)
self.setHeaderLabels(('name', 'widget'))
self.setSelectionMode(self.SingleSelection)
self.setDragEnabled(True)
self.setDropIndicatorShown(True)
self.setDragDropMode(self.InternalMove)
self.reparented_widgets = {}
def dropEvent(self, event):
index = self.indexAt(event.pos())
parent = index.parent()
self.model().dropMimeData(
event.mimeData(),
event.dropAction(),
index.row(),
index.column(),
parent
)
event.accept()
class TreeUI(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(TreeUI, self).__init__(parent)
widget = QtWidgets.QWidget(self)
self.setCentralWidget(widget)
tree = Tree()
for x in range(0, 6):
item = QtWidgets.QTreeWidgetItem(tree, ('item{}'.format(x), None))
item.setFlags(item.flags() & ~QtCore.Qt.ItemIsDropEnabled)
button = QtWidgets.QPushButton('Button{}'.format(x))
tree.setItemWidget(item, 1, button)
layout = QtWidgets.QVBoxLayout(widget)
layout.addWidget(tree)
main()
UPDATE #1:
I'm able to store the widgets for the QTreeWidgetItem within the startDrag function, while removing them from the item. But then, when I go to add them back to the new QTreeWidgetItem, the application crashes, unfortunately...
def startDrag(self, actions):
column_count = self.columnCount()
items = self.selectedItems()
for item in items:
for x in range(column_count):
widget = self.itemWidget(item, x)
if widget:
self.removeItemWidget(item, x)
self.reparent_widgets[x] = widget
super(Tree, self).startDrag(actions)
def dropEvent(self, event):
# Fix Mac/Maya drag and drop bug
index = self.indexAt(event.pos())
parent = index.parent()
self.model().dropMimeData(
event.mimeData(),
event.dropAction(),
index.row(),
index.column(),
parent
)
event.accept()
# Re-create widget(s)
pos = event.pos()
item = self.itemAt(pos)
for x in self.reparent_widgets.keys():
self.setItemWidget(item, x, self.reparent_widgets[x])

Related

Overriding QCompleter popup position

There have been similar questions asked about overriding the QCompleter popup position but i'll still not found a working solution. I simply want to move the popup down around 5px (I have some specific styling requirements)
I've tried subclassing a QListView and using that as my popup using setPopup(). I then override the showEvent and move the popup down in Y. I also do this on the resizeEvent since I believe this is triggered when items are filtered and the popup resizes. However this doesn't work.. I then used a singleshot timer to trigger the move after 1ms. This does kind of work but it seems quite inconsistent - the first time it shows is different to subsequent times or resizing.
Below is my latest attempt (trying to hack it by counting the number of popups..), hopefully someone can show me what i'm doing wrong or a better solution
import sys
import os
from PySide2 import QtCore, QtWidgets, QtGui
class QPopup(QtWidgets.QListView):
def __init__(self, parent=None):
super(QPopup, self).__init__(parent)
self.popups = 0
def offset(self):
y = 3 if self.popups < 2 else 7
print('y: {}'.format(y))
self.move(self.pos().x(), self.pos().y() + y)
self.popups += 1
def showEvent(self, event):
print('show')
# self.offset()
QtCore.QTimer.singleShot(1, self.offset)
def resizeEvent(self, event):
print('resize')
# self.offset()
QtCore.QTimer.singleShot(1, self.offset)
class MyDialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super(MyDialog, self).__init__(parent)
self.create_widgets()
self.create_layout()
self.create_connections()
def create_widgets(self):
self.le = QtWidgets.QLineEdit('')
self.completer = QtWidgets.QCompleter(self)
self.completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.completer.setCompletionMode(QtWidgets.QCompleter.PopupCompletion)
self.completer.setMaxVisibleItems(10)
self.completer.setFilterMode(QtCore.Qt.MatchContains)
self.completer.setPopup(QPopup())
popup = QPopup(self)
self.completer.setPopup(popup)
self.model = QtCore.QStringListModel()
self.completer.setModel(self.model)
self.le.setCompleter(self.completer)
self.completer.model().setStringList(['one','two','three'])
def create_layout(self):
main_layout = QtWidgets.QVBoxLayout(self)
main_layout.addWidget(self.le)
def create_connections(self):
pass
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
my_dialog = MyDialog()
my_dialog.show() # Show the UI
sys.exit(app.exec_())
One solution could be to make a subclass of QLineEdit and override keyPressEvent to display the popup with an offset:
PySide2.QtWidgets.QCompleter.complete([rect=QRect()])
For PopupCompletion and QCompletion::UnfilteredPopupCompletion modes, calling this function displays the popup displaying the current completions. By default, if rect is not specified, the popup is displayed on the bottom of the widget() . If rect is specified the popup is displayed on the left edge of the rectangle.
see doc.qt.io -> QCompleter.complete.
Complete, self-contained example
The rect is calculated based on the y-position of the cursor rect. The height of the popup window is not changed. The width is adjusted to the width of the ZLineEdit widget.
rect = QtCore.QRect(0,
self.cursorRect().y() + 4,
self.width(),
self.completer().widget().height())
Your code, slightly modified using the points mentioned above, could look like this:
import sys
from PySide2 import QtCore, QtWidgets
from PySide2.QtWidgets import QLineEdit, QDialog, QCompleter
class ZLineEdit(QLineEdit):
def __init__(self, string, parent=None):
super().__init__(string, parent)
def keyPressEvent(self, event):
super().keyPressEvent(event)
if len(self.text()) > 0:
rect = QtCore.QRect(0,
self.cursorRect().y() + 4,
self.width(),
self.completer().widget().height())
self.completer().complete(rect)
class MyDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.le = ZLineEdit('')
autoList = ['one', 'two', 'three']
self.completer = QCompleter(autoList, self)
self.setup_widgets()
self.create_layout()
self.create_connections()
def setup_widgets(self):
self.completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.completer.setCompletionMode(QtWidgets.QCompleter.PopupCompletion)
self.completer.setMaxVisibleItems(10)
self.completer.setFilterMode(QtCore.Qt.MatchContains)
self.le.setCompleter(self.completer)
def create_layout(self):
main_layout = QtWidgets.QVBoxLayout(self)
main_layout.addWidget(self.le)
def create_connections(self):
pass
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
my_dialog = MyDialog()
my_dialog.show()
sys.exit(app.exec_())
Test
On the left side you see the default behavior. On the right side the popup is moved down 4px:

Qt: Prevent drag-and-drop on child widgets and show forbidden cursor

I want to enable drag and drop functionality in some custom widgets, to allow reordering and rearranging the widgets within a layout. The basic functionality is working, but I'd like to prevent dropping a widget on itself, or on a child of itself. This is straightforward in the dropEvent method, but I can't find a way to also show the "forbidden" cursor while dragging, such that the user is aware that a drop will not be allowed.
The example below shows a test implementation, where the widgets "One" to "Five" can be dragged and dropped (no rearrangement will happen, only a message will be printed on the terminal, you may need to press Ctrl or something to initiate a drag). The problem line is the first ev.accept() in the dragEnterEvent method. By accepting the event, the cursor is shown in an "allowed" state (a grabbing hand for me). For example, trying to drag "One" and drop it onto "Three" appears as allowed, although nothing will happen. However, ignoring the event results in the event being propagated to the parent, so in that case dragging "Three" and dropping it onto "Three" results in "One" getting the drop instead. Setting the WA_NoMousePropagation attribute does not seem to make any difference.
So, what I would need is a way to "accept" the event, so that it will not be propagated to the parent, but still show a "forbidden" cursor, as if nobody accepted the event. Any ideas?
#!/usr/bin/env python3
import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
class WidgetMimeData(QtCore.QMimeData):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.itemObject = None
def hasFormat(self, mime):
if (self.itemObject and (mime == 'widgetitem')):
return True
return super().hasFormat(mime)
def setItem(self, obj):
self.itemObject = obj
def item(self):
return self.itemObject
class DraggableWidget(QGroupBox):
def __init__(self):
QWidget.__init__(self)
layout = QVBoxLayout()
self.setLayout(layout)
self.setAcceptDrops(True)
def addWidget(self, widget):
return self.layout().addWidget(widget)
def mouseMoveEvent(self, ev):
pixmap = QPixmap(self.size())
pixmap.fill(QtCore.Qt.transparent)
painter = QPainter()
painter.begin(pixmap)
painter.setOpacity(0.8)
painter.drawPixmap(0, 0, self.grab())
painter.end()
drag = QDrag(self)
mimedata = WidgetMimeData()
mimedata.setItem(self)
drag.setMimeData(mimedata)
drag.setPixmap(pixmap)
drag.setHotSpot(ev.pos())
drag.exec_(QtCore.Qt.MoveAction)
def dragEnterEvent(self, ev):
item = ev.mimeData().item()
if item.isAncestorOf(self):
#ev.ignore()
ev.accept()
else:
ev.accept()
def dropEvent(self, ev):
item = ev.mimeData().item()
if not item.isAncestorOf(self):
print('dropped on', self.layout().itemAt(0).widget().text())
ev.accept()
class HelloWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
w1 = DraggableWidget()
w1.addWidget(QLabel('One'))
w2 = DraggableWidget()
w2.addWidget(QLabel('Two'))
w3 = DraggableWidget()
w3.addWidget(QLabel('Three'))
w4 = DraggableWidget()
w4.addWidget(QLabel('Four'))
w5 = DraggableWidget()
w5.addWidget(QLabel('Five'))
w1.addWidget(w3)
w1.addWidget(w4)
w2.addWidget(w5)
layout = QVBoxLayout()
layout.addWidget(w1)
layout.addWidget(w2)
layout.addStretch(1)
centralWidget = QWidget(self)
centralWidget.setLayout(layout)
self.setCentralWidget(centralWidget)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
mainWin = HelloWindow()
mainWin.show()
sys.exit( app.exec_() )
Probably the easiest way is to always accept the event in dragEnterEvent and in dragMoveEvent ignore it when the source of the event is an ancestor of self, i.e.
def dragEnterEvent(self, ev):
ev.accept()
def dragMoveEvent(self, ev):
item = ev.source()
if item.isAncestorOf(self):
ev.ignore()
By ignoring the event in dragMoveEvent you wouldn't need the check in dropEvent either and can simply do
def dropEvent(self, ev):
print('Dropped of', self.layout().itemAt(0).widget().text())
ev.accept()

How do I make a context menu for each item in a QListWidget?

I'm working on a QGIS plugin, where the UI is made with PyQt. I have a QListWidget and a function that fills it. I'd like to add a context menu for each item with only one option: to open another window.
I'm having trouble searching for info, since most of it works only on PyQt4 and I'm using version 5. The QListWidget that I want to add a context menu on is ds_list_widget. Here's some of the relevant code.
FORM_CLASS, _ = uic.loadUiType(os.path.join(
os.path.dirname(__file__), 'dialog_base.ui'))
class Dialog(QDialog, FORM_CLASS):
def __init__(self, parent=None):
...
self.p_list_widget = self.findChild(QListWidget, 'projects_listWidget')
self.p_list_widget.itemClicked.connect(self.project_clicked)
self.ds_list_widget = self.findChild(QListWidget, 'datasets_listWidget')
self.ds_list_widget.itemClicked.connect(self.dataset_clicked)
...
def project_clicked(self, item):
self.fill_datasets_list(str(item.data(Qt.UserRole)))
self.settings.setValue('projectIdValue', str(item.data(Qt.UserRole)))
def fill_datasets_list(self, project_id):
self.ds_list_widget.clear()
dataset_list = self.anotherClass.fetch_dataset_list(project_id)
for dataset in dataset_list:
#Query stuff from remote
...
item = QListWidgetItem(ds_name, self.ds_list_widget)
item.setIcon(self.newIcon(ds_img))
item.setData(Qt.UserRole, ds_id)
self.ds_list_widget.addItem(item)
self.ds_list_widget.setIconSize(self.iconSize)
Since your list-widget is created by Qt Designer, it is probably easiest to install an event-filter on it and trap the context-menu event. With that in place, the rest is quite straightforward - here is a simple demo:
import sys
from PyQt5 import QtCore, QtWidgets
class Dialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__()
self.listWidget = QtWidgets.QListWidget()
self.listWidget.addItems('One Two Three'.split())
self.listWidget.installEventFilter(self)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.listWidget)
def eventFilter(self, source, event):
if (event.type() == QtCore.QEvent.ContextMenu and
source is self.listWidget):
menu = QtWidgets.QMenu()
menu.addAction('Open Window')
if menu.exec_(event.globalPos()):
item = source.itemAt(event.pos())
print(item.text())
return True
return super(Dialog, self).eventFilter(source, event)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Dialog()
window.setGeometry(600, 100, 300, 200)
window.show()
sys.exit(app.exec_())
PS:
You should also note that code like this:
self.p_list_widget = self.findChild(QListWidget, 'projects_listWidget')
is completely unnecessary. All the widgets from Qt Designer are automatically added as attributes to the form class using the object-name. So your code can be simplified to this:
self.projects_listWidget.itemClicked.connect(self.project_clicked)
self.datasets_listWidget.itemClicked.connect(self.dataset_clicked)
there is no need to use findChild.
In addition to the answer above, you can also set multiple QAction() submenu items to do multiple things. As you would a normal menu.
One way is to edit your eventFilter so that menu.exec() becomes a variable:
def eventFilter(self, source, event):
if (event.type() == QtCore.QEvent.ContextMenu and source is self.listWidget):
menu = QtWidgets.QMenu()
open_window_1 = QAction("Open Window 1")
open_window_2 = QAction("Open Window 2")
menu.addAction(open_window_1)
menu.addAction(open_window_2)
menu_click = menu.exec(event.globalPos())
try:
item = source.itemAt(event.pos())
except Exception as e:
print(f"No item selected {e}")
if menu_click == open_window_1 :
print("Opening Window 1...")
# Your code here
if menu_click == open_window_2 :
print("Opening Window 2...")
# Your code here
# and so on... You can now add as many items as you want
return True
return super(Dialog, self).eventFilter(source, event)

Drag and drop columns between QHeaderView and QListWidget

I am having troubled using the QHeaderView drag & drop feature. When I subclass a QHeaderView, I am able to accept drops with no issue. However, when I click on the QHeaderView and try to drag from one of the columns, nothing appears to happen.
Below I have re-implemented several drag events to simply print if they were called. However, only the dragEnterEvent is successful. No other event such as startDrag is ever called. My ultimate goal is to have a QTableView where I can drag columns from and to a QListWidget (essentially hiding the column) and the user can then drag the QListWidget item back onto the QTableView if they want the column and its data to be visible again. However, I can’t move forward until I can understand why the QHeaderView is not allowing me to drag. Any help would be greatly appreciated.
class MyHeader(QHeaderView):
def __init__(self, parent=None):
super().__init__(Qt.Horizontal, parent)
self.setDragEnabled(True)
self.setAcceptDrops(True)
def startDrag(self, *args, **kwargs):
print('start drag success')
def dragEnterEvent(self, event):
print('drag enter success')
def dragLeaveEvent(self, event):
print('drag leave success')
def dragMoveEvent(self, event):
print('drag move success')
class Form(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
listWidget = QListWidget()
listWidget.setDragEnabled(True)
listWidget.setAcceptDrops(True)
listWidget.addItem('item #1')
listWidget.addItem('item #2')
tableWidget = QTableWidget()
header = MyHeader()
tableWidget.setHorizontalHeader(header)
tableWidget.setRowCount(5)
tableWidget.setColumnCount(2)
tableWidget.setHorizontalHeaderLabels(["Column 1", "Column 2"])
splitter = QSplitter(Qt.Horizontal)
splitter.addWidget(listWidget)
splitter.addWidget(tableWidget)
layout = QHBoxLayout()
layout.addWidget(splitter)
self.setLayout(layout)
if __name__=='__main__':
import sys
app = QApplication(sys.argv)
form= Form()
form.show()
sys.exit(app.exec_())
The QHeaderView class does not use the drag and drop methods inherited from QAbstractItemView, because it never needs to initiate a drag operation. Drag and drop is only used for rearranging columns, and it is not necessary to use the QDrag mechanism for that.
Given this, it will be necessary to implement custom drag and drop handling (using mousePressEvent, mouseMoveEvent and dropEvent), and also provide functions for encoding and decoding the mime-data format that Qt uses to pass items between views. An event-filter will be needed for the table-widget, so that dropping is still possible when all columns are hidden; and also for the list-widget, to stop it copying items to itself.
The demo script below implements all of that. There are probably some more refinements needed, but it should be enough to get you started:
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class MyHeader(QHeaderView):
MimeType = 'application/x-qabstractitemmodeldatalist'
columnsChanged = pyqtSignal(int)
def __init__(self, parent=None):
super().__init__(Qt.Horizontal, parent)
self.setDragEnabled(True)
self.setAcceptDrops(True)
self._dragstartpos = None
def encodeMimeData(self, items):
data = QByteArray()
stream = QDataStream(data, QIODevice.WriteOnly)
for column, label in items:
stream.writeInt32(0)
stream.writeInt32(column)
stream.writeInt32(2)
stream.writeInt32(int(Qt.DisplayRole))
stream.writeQVariant(label)
stream.writeInt32(int(Qt.UserRole))
stream.writeQVariant(column)
mimedata = QMimeData()
mimedata.setData(MyHeader.MimeType, data)
return mimedata
def decodeMimeData(self, mimedata):
data = []
stream = QDataStream(mimedata.data(MyHeader.MimeType))
while not stream.atEnd():
row = stream.readInt32()
column = stream.readInt32()
item = {}
for count in range(stream.readInt32()):
key = stream.readInt32()
item[key] = stream.readQVariant()
data.append([item[Qt.UserRole], item[Qt.DisplayRole]])
return data
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self._dragstartpos = event.pos()
super().mousePressEvent(event)
def mouseMoveEvent(self, event):
if (event.buttons() & Qt.LeftButton and
self._dragstartpos is not None and
(event.pos() - self._dragstartpos).manhattanLength() >=
QApplication.startDragDistance()):
column = self.logicalIndexAt(self._dragstartpos)
data = [column, self.model().headerData(column, Qt.Horizontal)]
self._dragstartpos = None
drag = QDrag(self)
drag.setMimeData(self.encodeMimeData([data]))
action = drag.exec(Qt.MoveAction)
if action != Qt.IgnoreAction:
self.setColumnHidden(column, True)
def dropEvent(self, event):
mimedata = event.mimeData()
if mimedata.hasFormat(MyHeader.MimeType):
if event.source() is not self:
for column, label in self.decodeMimeData(mimedata):
self.setColumnHidden(column, False)
event.setDropAction(Qt.MoveAction)
event.accept()
else:
event.ignore()
else:
super().dropEvent(event)
def setColumnHidden(self, column, hide=True):
count = self.count()
if 0 <= column < count and hide != self.isSectionHidden(column):
if hide:
self.hideSection(column)
else:
self.showSection(column)
self.columnsChanged.emit(count - self.hiddenSectionCount())
class Form(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.listWidget = QListWidget()
self.listWidget.setAcceptDrops(True)
self.listWidget.setDragEnabled(True)
self.listWidget.viewport().installEventFilter(self)
self.tableWidget = QTableWidget()
header = MyHeader(self)
self.tableWidget.setHorizontalHeader(header)
self.tableWidget.setRowCount(5)
self.tableWidget.setColumnCount(4)
labels = ["Column 1", "Column 2", "Column 3", "Column 4"]
self.tableWidget.setHorizontalHeaderLabels(labels)
for column, label in enumerate(labels):
if column > 1:
item = QListWidgetItem(label)
item.setData(Qt.UserRole, column)
self.listWidget.addItem(item)
header.hideSection(column)
header.columnsChanged.connect(
lambda count: self.tableWidget.setAcceptDrops(not count))
self.tableWidget.viewport().installEventFilter(self)
splitter = QSplitter(Qt.Horizontal)
splitter.addWidget(self.listWidget)
splitter.addWidget(self.tableWidget)
layout = QHBoxLayout()
layout.addWidget(splitter)
self.setLayout(layout)
def eventFilter(self, source, event):
if event.type() == QEvent.Drop:
if source is self.tableWidget.viewport():
self.tableWidget.horizontalHeader().dropEvent(event)
return True
else:
event.setDropAction(Qt.MoveAction)
return super().eventFilter(source, event)
if __name__=='__main__':
app = QApplication(sys.argv)
form = Form()
form.setGeometry(600, 50, 600, 200)
form.show()
sys.exit(app.exec_())

dropEvent() not getting called

I am trying to perform a drag and drop operation from a QTreeWidget to QGraphicsView. dragStart() works, and dragEnterEvent() works, but dropEvent() is never being called. Also the pixmap is not showing up until the cursor enters the QGraphicsView, which isn't a problem, but I just thought it would appear as soon as the drag started. Here is my startDrag function:
def on_list_startDrag(self, supportedActions):
#Retreive the item that was clicked on
currentPart = self.ui.list.currentItem()
part = currentPart.text(0)
drag = QtGui.QDrag(self.ui.list)
mime = QtCore.QMimeData()
print(part)
#retreive that associated graphics file
icon = QtGui.QIcon('drawings/FULL/' + part + '.svg')
pixmap = icon.pixmap(102,122)
selected = QtGui.QImage('drawings/FULL/' + part + '.svg')
data = pickle.dumps(selected)
mime.setData('application/x-item', data)
#mime.setImageData(QtGui.QImage('drawings/FULL/' + part + '.svg'))
drag.setMimeData(mime)
drag.setHotSpot(QtCore.QPoint(pixmap.width()/2, pixmap.height()/2))
drag.setPixmap(pixmap)
drag.exec_()
Here is the the dragEnterEvent:
def on_workArea_dragEnterEvent(self, event):
print(event.format())
if (event.mimeData().hasFormat('application/x-item')):
event.accept()
print('accepted')
else:
event.ignore()
Finally the dropEvent code:
def on_workArea_dropEvent(self, event):
print('dropped')
When I start the drag and drop operation is happening the cursor has the circle with the slash like the widget doesn't accept drops, but I set the QGraphicsView, workArea, to accept drops. Can someone please help me get the drop working and explain why the pixmap doesn't show up behind the cursor until the cursor is over the QGraphicsView. Thank you.
You need to implement dragMoveEvent() as well, or dropEvent() won't be called. This is also what causes it to show a proper drop icon, instead of the slashed-circle "can't drop here" icon.
I've checked your code and it does look and work fine for me; both dropEvent and pixmap work as expected. Perhaps there's smth else in your code which causes this unwanted behaviour you're describing. As for the dropEvent, you might have problems connecting slot to a signal, which leads to your code not being called. I've made a small example which does drag and drop between treeview and grahicsview and loads and presents a pixmap:
import sys
from PyQt4 import QtGui, QtCore
class TestTreeView(QtGui.QTreeView):
def __init__(self, parent = None):
super(TestTreeView, self).__init__(parent)
self.setDragEnabled(True)
def startDrag(self, dropAction):
print('tree start drag')
icon = QtGui.QIcon('/home/image.png')
pixmap = icon.pixmap(64, 64)
mime = QtCore.QMimeData()
mime.setData('application/x-item', '???')
drag = QtGui.QDrag(self)
drag.setMimeData(mime)
drag.setHotSpot(QtCore.QPoint(pixmap.width()/2, pixmap.height()/2))
drag.setPixmap(pixmap)
drag.start(QtCore.Qt.CopyAction)
class TestGraphicsView(QtGui.QGraphicsView):
def __init__(self, parent = None):
super(TestGraphicsView, self).__init__(parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
print('graphics view drag enter')
if (event.mimeData().hasFormat('application/x-item')):
event.acceptProposedAction()
print('accepted')
else:
event.ignore()
def dropEvent(self, event):
print('graphics view drop')
event.acceptProposedAction()
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
self.model = QtGui.QStandardItemModel()
for k in range(0, 4):
parentItem = self.model.invisibleRootItem()
for i in range(0, 4):
item = QtGui.QStandardItem(QtCore.QString("item %0 %1").arg(k).arg(i))
parentItem.appendRow(item)
parentItem = item
self.setMinimumSize(300, 400)
self.view = TestTreeView(self)
self.view.setModel(self.model)
self.view.setMinimumSize(300, 200)
self.graphicsView = TestGraphicsView(self)
self.graphicsView.setGeometry(0, 210, 300, 400)
self.layout = QtGui.QVBoxLayout(self.centralWidget())
self.layout.addWidget(self.view)
self.layout.addWidget(self.graphicsView)
def main():
app = QtGui.QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()
if __name__ == '__main__':
main()
hope this helps, regards

Categories