PyQt: How to get QListWidget's listItem .data() on dropEvent - python

There are two QListWidgets. Every list item was assigned MyClass()'s instance using setData(QtCore.Qt.UserRole, myClassInstA).
Clicking a lower QListWidget's listItem prints out a clicked listItem's data retrieved using:
.data(QtCore.Qt.UserRole).toPyObject()
Any itemA dragged and dropped from top QListWidget onto a lower shows None for data.
Interesting that clicking the same item prints there is a data. I wonder if it is possible to retrieve a data stored in listItem within droppedOnB() function (so droppedOnB() is able to print out the data stored in a item).
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)
self._dropping = False
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)
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)
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')
self.listWidgetB.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
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('B'+'%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.listWidgetB, QtCore.SIGNAL("dropped"), self.droppedOnB)
self.listWidgetB.clicked.connect(self.itemClicked)
def droppedOnB(self, dropped_list):
print '\n\t droppedOnB()', dropped_list, dropped_list[-1]
destIndexes=dropped_list[-1]
for index in range(destIndexes[0],destIndexes[-1]+1):
dropedItem=self.listWidgetB.item(index)
modelIndex=self.listWidgetB.indexFromItem(dropedItem)
dataObject = modelIndex.data(QtCore.Qt.UserRole).toPyObject()
print '\n\t\t droppedOnB()', type(modelIndex), type(dataObject)
def itemClicked(self, modelIndex):
dataObject = modelIndex.data(QtCore.Qt.UserRole).toPyObject()
print 'itemClicked(): ' ,type(modelIndex), type(dataObject)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(720,480)
sys.exit(app.exec_())

The ultimate goal was to replace MyClassA's instance data-object (attached to itemA) with MyClassB after itemA is dropped onto listWidgetB.
When itemA is dropped onto the destination listWidgetB the itemA arrives with no data stored. It returns None if you try to retrieve it with itemA.data(QtCore.Qt.UserRole).toPyObject() (if done inside of droppedOnB() - a method triggered first onDrop event).
Trying to assign, reassign a data to just dropped listItem... or even removing it causes all kind of surprises later. I am using .setHidden(True).
Those are the steps:
Get source listItem and its data.
Get destination (dropped) item and hide it.
Declare MyClassB() instance
Create new list item. Assign created in previous step MyClassB() instance object to listItem using .setData(QtCore.Qt.UserRole, myClassInstB)
Add new listItem to ListWidget.
Here is a functional code. Once again, itemA is assign an instance of ClassA on creation.
After itemA is dropped onto listWidgetB a dropped item is hidden and 'substituted' with another item to which classB instance is assigned.
from PyQt4 import QtGui, QtCore
import sys, os, copy
class MyClassA(object):
def __init__(self):
super(MyClassA, self).__init__()
class MyClassB(object):
def __init__(self):
super(MyClassB, self).__init__()
self.DataObjectCopy=None
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)
self._dropping = False
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)
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)
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')
self.listWidgetB.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
for i in range(3):
listItemA=QtGui.QListWidgetItem()
listItemA.setText('A'+'%04d'%i)
self.listWidgetA.addItem(listItemA)
myClassInstA=MyClassA()
listItemA.setData(QtCore.Qt.UserRole, myClassInstA)
listItemB=QtGui.QListWidgetItem()
listItemB.setText('B'+'%04d'%i)
self.listWidgetB.addItem(listItemB)
myClassInstB=MyClassB()
listItemB.setData(QtCore.Qt.UserRole, myClassInstB)
myBoxLayout.addWidget(self.listWidgetA)
myBoxLayout.addWidget(self.listWidgetB)
self.connect(self.listWidgetB, QtCore.SIGNAL("dropped"), self.droppedOnB)
self.listWidgetB.clicked.connect(self.itemClicked)
def droppedOnB(self, dropped_list):
if not dropped_list or len(dropped_list)<3: return
srcIndexes=dropped_list[1:-1]
destIndexes=dropped_list[-1]
# build a list of corresponding src-to-dest indexes sets
itemsIndxes=[]
i=0
for num in range(destIndexes[0], destIndexes[-1]+1):
itemsIndxes.append((srcIndexes[i], num))
i+=1
print '\n\t droppedOnB(): dropped_list =',dropped_list,'; srcIndexes =',srcIndexes,'; destIndexes =',destIndexes, '; itemsIndxes =',itemsIndxes
for indexSet in itemsIndxes:
srcNum = indexSet[0]
destIndxNum = indexSet[-1]
# Get source listItem's data object
srcItem=self.listWidgetA.item(srcNum)
if not srcItem: continue
srcItemData = srcItem.data(QtCore.Qt.UserRole)
if not srcItemData: continue
srcItemDataObject=srcItemData.toPyObject()
if not srcItemDataObject: continue
# make a deepcopy of src data object
itemDataObject_copy=copy.deepcopy(srcItemDataObject)
# get dropped item
droppedItem=self.listWidgetB.item(destIndxNum)
# hide dropped item since removing it results to mess
droppedItem.setHidden(True)
# declare new ClassB instance
myClassInstB=MyClassB()
myClassInstB.DataObjectCopy=itemDataObject_copy
# create a new listItem
newListItem=QtGui.QListWidgetItem()
newListItem.setData(QtCore.Qt.UserRole, myClassInstB)
newListItem.setText(srcItem.text())
self.listWidgetB.blockSignals(True)
self.listWidgetB.addItem(newListItem)
self.listWidgetB.blockSignals(False)
def itemClicked(self, modelIndex):
dataObject = modelIndex.data(QtCore.Qt.UserRole).toPyObject()
print 'itemClicked(): instance type:', type(dataObject)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
dialog_1 = Dialog_01()
dialog_1.show()
dialog_1.resize(720,480)
sys.exit(app.exec_())

Related

How to add a menu only in the QTreeWidgetItem after pressing the right click? [duplicate]

I have the following code to create a QTreeWidget and a contextmenu with 2 actions.
import sys
from PyQt5 import QtCore, QtWidgets
class Dialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__()
self.tw = QtWidgets.QTreeWidget()
self.tw.setHeaderLabels(['Name', 'Cost ($)'])
cg = QtWidgets.QTreeWidgetItem(['carrots', '0.99'])
c1 = QtWidgets.QTreeWidgetItem(['carrot', '0.33'])
self.tw.addTopLevelItem(cg)
self.tw.addTopLevelItem(c1)
self.tw.installEventFilter(self)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.tw)
def eventFilter(self, source: QtWidgets.QTreeWidget, event):
if (event.type() == QtCore.QEvent.ContextMenu and
source is self.tw):
menu = QtWidgets.QMenu()
AAction = QtWidgets.QAction("AAAAA")
AAction.triggered.connect(lambda :self.a(source.itemAt(event.pos())))
BAction = QtWidgets.QAction("BBBBBB")
BAction.triggered.connect(lambda :self.b(source, event))
menu.addAction(AAction)
menu.addAction(BAction)
menu.exec_(event.globalPos())
return True
return super(Dialog, self).eventFilter(source, event)
def a(self, item):
if item is None:
return
print("A: {}".format([item.text(i) for i in range(self.tw.columnCount())]))
def b(self, source, event):
item = source.itemAt(event.pos())
if item is None:
return
print("B: {}".format([item.text(i) for i in range(source.columnCount())]))
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = Dialog()
window.setGeometry(600, 100, 300, 200)
window.show()
sys.exit(app.exec_())
When opening the contextmenu in the header and clicking on one of the actions it prints either carrot or carrots, depending on where in the contextmenu I click. But I give the position of right click event to the functions.
So why is this happening and what can I do to stop it?
Your code has 2 errors:
The main error is that the itemAt() method uses the coordinates with respect to the viewport() and not with respect to the view (the QTreeWidget) so you will get incorrect items (the header occupies a space making the positions with respect to the QTreeWidget and the viewport() have an offset).
You should not block the eventloop, for example blocking the eventFilter you may be blocking other events that would cause errors that are difficult to debug, in this case it is better to use a signal.
class Dialog(QtWidgets.QDialog):
rightClicked = QtCore.pyqtSignal(QtCore.QPoint)
def __init__(self, parent=None):
super(Dialog, self).__init__()
self.tw = QtWidgets.QTreeWidget()
self.tw.setHeaderLabels(["Name", "Cost ($)"])
cg = QtWidgets.QTreeWidgetItem(["carrots", "0.99"])
c1 = QtWidgets.QTreeWidgetItem(["carrot", "0.33"])
self.tw.addTopLevelItem(cg)
self.tw.addTopLevelItem(c1)
self.tw.viewport().installEventFilter(self)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.tw)
self.rightClicked.connect(self.handle_rightClicked)
def eventFilter(self, source: QtWidgets.QTreeWidget, event):
if event.type() == QtCore.QEvent.ContextMenu and source is self.tw.viewport():
self.rightClicked.emit(event.pos())
return True
return super(Dialog, self).eventFilter(source, event)
def handle_rightClicked(self, pos):
item = self.tw.itemAt(pos)
if item is None:
return
menu = QtWidgets.QMenu()
print_action = QtWidgets.QAction("Print")
print_action.triggered.connect(lambda checked, item=item: self.print_item(item))
menu.addAction(print_action)
menu.exec_(self.tw.viewport().mapToGlobal(pos))
def print_item(self, item):
if item is None:
return
texts = []
for i in range(item.columnCount()):
text = item.text(i)
texts.append(text)
print("B: {}".format(",".join(texts)))
Although it is unnecessary that you use an eventFilter to handle the contextmenu since a simpler solution is to set the contextMenuPolicy of the QTreeWidget to Qt::CustomContextMenu and use the customContextMenuRequested signal:
class Dialog(QtWidgets.QDialog):
def __init__(self, parent=None):
super(Dialog, self).__init__()
self.tw = QtWidgets.QTreeWidget()
self.tw.setHeaderLabels(["Name", "Cost ($)"])
cg = QtWidgets.QTreeWidgetItem(["carrots", "0.99"])
c1 = QtWidgets.QTreeWidgetItem(["carrot", "0.33"])
self.tw.addTopLevelItem(cg)
self.tw.addTopLevelItem(c1)
self.tw.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.tw.customContextMenuRequested.connect(self.handle_rightClicked)
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.tw)
def handle_rightClicked(self, pos):
item = self.tw.itemAt(pos)
if item is None:
return
menu = QtWidgets.QMenu()
print_action = QtWidgets.QAction("Print")
print_action.triggered.connect(lambda checked, item=item: self.print_item(item))
menu.addAction(print_action)
menu.exec_(self.tw.viewport().mapToGlobal(pos))
def print_item(self, item):
if item is None:
return
texts = []
for i in range(item.columnCount()):
text = item.text(i)
texts.append(text)
print("B: {}".format(",".join(texts)))

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_())

Get drag-n-drop qtreewidget items - Python

Is there a way I can get the items being drag/dropped and their destination parent?
In an ideal scenario what I want to happen is once the dropEvent finishes, it prints the qtreewidgetitems which were moved, as well as the new parent which the items were moved to. The parent would either be the qtreewidget itself or another qtreewidgetitem depending on where the drop happened.
Can someone help me out here please?
Below is the code i have so far.
# Imports
# ------------------------------------------------------------------------------
import sys
from PySide import QtGui, QtCore, QtSvg
class TreeNodeItem( QtGui.QTreeWidgetItem ):
def __init__( self, parent, name="" ):
super( TreeNodeItem, self ).__init__( parent )
self.setText( 0, name )
self.stuff = "Custom Names - " + str(name)
class TreeWidget(QtGui.QTreeWidget):
def __init__(self, parent=None):
QtGui.QTreeWidget.__init__(self, parent)
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setItemsExpandable(True)
self.setAnimated(True)
self.setDragEnabled(True)
self.setDropIndicatorShown(True)
self.setDragDropMode(QtGui.QAbstractItemView.InternalMove)
self.setAlternatingRowColors(True)
# def dropEvent(self, event):
# print "finished"
def dropEvent(self, event):
return_val = super( TreeWidget, self ).dropEvent( event )
print ("Drop finished")
d = event.mimeData()
print d, event.source()
return return_val
# Main
# ------------------------------------------------------------------------------
class ExampleWidget(QtGui.QWidget):
def __init__(self,):
super(ExampleWidget, self).__init__()
self.initUI()
def initUI(self):
# formatting
self.resize(250, 400)
self.setWindowTitle("Example")
# widget - passes treewidget
self.itemList = QtGui.QTreeWidget()
self.itemList = TreeWidget()
headers = [ "Items" ]
self.itemList.setColumnCount( len(headers) )
self.itemList.setHeaderLabels( headers )
# layout Grid - row/column/verticalpan/horizontalspan
self.mainLayout = QtGui.QGridLayout(self)
self.mainLayout.setContentsMargins(5,5,5,5)
self.mainLayout.addWidget(self.itemList, 0,0,1,1)
# display
self.show()
# Functions
# --------------------------------------------------------------------------
def closeEvent(self, event):
print "closed"
def showEvent(self, event):
print "open"
for i in xrange(20):
TreeNodeItem( parent=self.itemList , name=str(i) )
# Main
# ------------------------------------------------------------------------------
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
ex = ExampleWidget()
sys.exit(app.exec_())
I would suggest using a View/Model approach.
Decoding the 'application/x-qabstractitemmodeldatalist' will only return the item dragged, and the dropMimeData isn't used in the QTreeWidget.
Look here for an example.
https://wiki.python.org/moin/PyQt/Handling%20Qt's%20internal%20item%20MIME%20type

Add a click on QLineEdit

I am working on set a click() event to QLineEdit, I already successfully did it. But I want to go back to Mainwindow when the QLine Edit is clicked because I need the data in Mainwindow to further process the data. But I failed to let it go back, neither nor to cite the Mainwindow as parent, I hope someone can point it out. Thank you so much.
MainWindow
{
...
self.tc = MyLineEdit(self.field[con.ConfigFields.VALUE])#self.tc = wx.TextCtrl(self.parent, -1, str(field[con.ConfigFields.VALUE]), pos=(x+220, y-3), size=(200, -1))
...
}
class MyLineEdit(QtGui.QLineEdit):
def __init__(self, parent=MainWindow):
super(MyLineEdit, self).__init__(parent)
#super(CustomQLineEidt, self).__init__()
def mousePressEvent(self, e):
self.mouseseleted()
def mouseseleted(self):
print "here"
MainWindow.mousePressEvent
I use the following to connect any method as the callback for a click event:
class ClickableLineEdit(QLineEdit):
clicked = pyqtSignal() # signal when the text entry is left clicked
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton: self.clicked.emit()
else: super().mousePressEvent(event)
To use:
textbox = ClickableLineEdit('Default text')
textbox.clicked.connect(someMethod)
Specifically for the op:
self.tc = ClickableLineEdit(self.field[con.ConfigFields.VALUE])
self.tc.clicked.connect(self.mouseseleted)
Just simply call the MainWindow mousePressEvent and give it the event variable the line edit received
class MyLineEdit(QtGui.QLineEdit):
def __init__(self, parent):
super(MyLineEdit, self).__init__(parent)
self.parentWindow = parent
def mousePressEvent(self, event):
print 'forwarding to the main window'
self.parentWindow.mousePressEvent(event)
Or you can connect a signal from the line edit
class MyLineEdit(QtGui.QLineEdit):
mousePressed = QtCore.pyqtProperty(QtGui.QMouseEvent)
def __init__(self, value):
super(MyLineEdit, self).__init__(value)
def mousePressEvent(self, event):
print 'forwarding to the main window'
self.mousePressed.emit(event)
Then just connect the signal in your main window where you created it
self.tc = MyLineEdit(self.field[con.ConfigFields.VALUE])#self.tc = wx.TextCtrl(self.parent, -1, str(field[con.ConfigFields.VALUE]), pos=(x+220, y-3), size=(200, -1))
self.tc.mousePressed[QtGui.QMouseEvent].connect(self.mousePressEvent)
This is what I used to do onClick for QLineEdits
class MyLineEdit(QtGui.QLineEdit):
def focusInEvent(self, e):
try:
self.CallBack(*self.CallBackArgs)
except AttributeError:
pass
super().focusInEvent(e)
def SetCallBack(self, callBack):
self.CallBack = callBack
self.IsCallBack = True
self.CallBackArgs = []
def SetCallBackArgs(self, args):
self.CallBackArgs = args
and in my MainGUI:
class MainGUI(..):
def __init__(...):
....
self.input = MyLineEdit()
self.input.SetCallBack(self.Test)
self.input.SetCallBackArgs(['value', 'test'])
...
def Test(self, value, test):
print('in Test', value, test)

PyQT: can't drag/drop plain text into browser form element, but i can back into a text editor

I've finally got a working example of both dragging AND dropping into & out of a listwidget, but sometimes the dragging into other contexts/applications doesn't work.
Example:
SUCCESS: select & drag text/plain from gedit into the listwidget and back to the text-editor
FAILURE: but I can't then drag the plain-text listwidgetitem into a chrome/pyqtwebview browser form element.
Goal:
I'd like to have an all-purpose drag-and-drop-box for inter-application transfer: images, urls, html & text, such that the appropriate content is delivered to the dropping-upon application's capabilities.
Code:
import datetime
import cPickle
import pickle
import sys
from PyQt4 import QtGui, QtCore
from PIL import Image, ImageQt
import urllib2 as urllib
class dropZone(QtGui.QListWidget):
def __init__(self, parent=None):
super(dropZone, self).__init__(parent)
self.setMinimumSize(400,480)
self.setDragEnabled(True)
self.setAcceptDrops(True)
self.setIconSize(QtCore.QSize(240, 240))
def dragEnterEvent(self, event):
print "hello draggin!"
print event.mimeData().text()
if event.mimeData().hasUrls():
event.accept()
elif event.mimeData().hasText():
event.accept()
elif event.mimeData().hasImage():
event.accept()
else:
event.ignore()
def dragMoveEvent(self, event):
if event.mimeData().hasUrls():
event.setDropAction(QtCore.Qt.MoveAction)
event.accept()
elif event.mimeData().hasText():
event.setDropAction(QtCore.Qt.MoveAction)
event.accept()
elif event.mimeData().hasImage():
event.setDropAction(QtCore.Qt.MoveAction)
event.accept()
else:
# event.ignore()
event.accept()
def dragLeaveEvent(self, event): #this doesn't get used unless the drag fails..
print "bye bye dragging";
event.accept()
def dragAway(self,event):
if not self.selectedIndexes(): return
drag = QtGui.QDrag(self)
#data = []
md = QtCore.QMimeData() #output setter
for index in self.selectedIndexes(): #right now we're just doing the last one..
if not index.isValid(): continue
txt = self.currentItem().text()
url = QtCore.QUrl(txt)
# url = QtCore.QUrl().fromUserInput(txt)
# if url.isValid():
if url.host() != "":
print "valid url:"+txt
urls = [ url ] #this is where we could have been dumping the urls in during the above loop
md.setUrls(urls)
elif txt != "":
txt = self.currentItem().text()
md.setText(txt)
if self.currentItem().icon() != None:
icon = self.currentItem().icon()
pixmap = icon.pixmap(QtCore.QSize(240, 240))
drag.setPixmap(pixmap) #what the user sees when dragging the object
else:
event.ignore()
print "output:"+md.formats().join(', ') #no img-data! Just urls!
# this is important. Without this, it won't do anything.
drag.setMimeData(md)
result = drag.exec_(QtCore.Qt.MoveAction)
if result: # == QtCore.Qt.MoveAction:
self.model().removeRow(index.row())
def mouseMoveEvent(self, event): #apparently the way to drag-off
self.dragAway(event)
def dropEvent(self, event):
txt = event.mimeData().text()
#need a better way to determine what to add?
if event.mimeData().hasImage():
qimg = event.mimeData().imageData().toPyObject()
qimg.scaled(QtCore.QSize(240, 240), Image.ANTIALIAS)
qpix = QtGui.QPixmap.fromImage(qimg) #ImageQt.ImageQt(picture)
icon = QtGui.QIcon(qpix) #QtGui.QPixmap.fromImage(ImageQt.ImageQt(qimg))
for url in event.mimeData().urls():
print url.toString()
item = QtGui.QListWidgetItem(url.toString(),self) #os.path.basename(url)
item.setIcon(icon)
elif event.mimeData().hasUrls():
for url in event.mimeData().urls():
print url.toString()
item = QtGui.QListWidgetItem(url.toString(),self) #os.path.basename(url)
# self.setText(url.toString())
event.accept()
elif event.mimeData().hasText():
item = QtGui.QListWidgetItem(txt,self) #os.path.basename(url)
event.accept()
else:
event.ignore()
class testDialog(QtGui.QDialog):
def __init__(self, parent=None):
super(testDialog, self).__init__(parent)
self.setWindowTitle("Drag Drop Test")
layout = QtGui.QGridLayout(self)
# self.model = simple_model()
self.listView = dropZone()
# self.listView.setModel(self.model) #preloading?
layout.addWidget(self.listView,0,1,2,2)
if __name__ == "__main__":
'''
the try catch here is to ensure that the app exits cleanly no matter what
makes life better for SPE
'''
try:
app = QtGui.QApplication([])
dl = testDialog()
dl.exec_()
except Exception, e: #could use as e for python 2.6...
print e
sys.exit(app.closeAllWindows())
It seems to work if you replace:
result = drag.exec_(QtCore.Qt.MoveAction)
with
result = drag.exec_(QtCore.Qt.CopyAction)

Categories