I am trying to create a QListWidget that has custom widgets within it, each containing a drag button. The idea is that the QListWidgetItem can only be dragged and dropped when the button within it called 'drag' is pressed down. Upon release of the mouse/button the QListWidgetItem would then drop into its place. This whole thing should act just like normal QListWidget, excepting only that the location of a mouse press must be on the button called 'drag'.
My current method is to set all QListWidgetItem flags to ~Qt.ItemIsDragEnabled upon initialization, and then turn this back on when the button is clicked. Then upon leaving the widget I turn drag back off.
Here is working code to demonstrate where I am. Obviously this isn't what I really want, but I can't figure out how to pass the mouse press event made within the 'drag' button on to the QListWidgetItem behind all in one click.
import sys
import os
from PyQt4 import QtGui
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class DragArea(QFrame):
"""docstring for DragButton"""
def __init__(self, parent=None, text='Test', index=None):
super(DragArea, self).__init__()
self.parent = parent
self.index = index
self.layout = QHBoxLayout()
self.setLayout(self.layout)
self.label = QLabel()
self.button = QPushButton()
self.label.setText(text)
self.button.setText('Drag')
self.layout.addWidget(self.label)
self.layout.addWidget(self.button)
self.button.pressed.connect(self.drag)
def drag(self):
item = self.parent.bodyMap[self.index]
item.setFlags(
Qt.ItemIsSelectable |
Qt.ItemIsEnabled |
Qt.ItemIsDragEnabled
)
def leaveEvent(self, event):
item = self.parent.bodyMap[self.index]
item.setFlags(
item.flags() &
~Qt.ItemIsSelectable &
~Qt.ItemIsEnabled &
~Qt.ItemIsDragEnabled
)
class QuoteArea(QListWidget):
def __init__(self, parent=None):
super(QuoteArea, self).__init__()
self.bodyMap = {}
self.setStyleSheet("""
QListWidget {
background: gray;
}
QListWidget::item:selected {
background: None;
}
""")
self.setDragDropMode(QAbstractItemView.InternalMove)
self.setDefaultDropAction(Qt.MoveAction)
self.setDragDropOverwriteMode(False)
self.setAcceptDrops(True)
self.setDropIndicatorShown(True)
self.setDragEnabled(True)
self.setSelectionRectVisible(False)
self.setResizeMode(QListView.Adjust)
self.setGeometry(30, 40, 400, 500)
for a in xrange(5):
self.addQuote(a)
def addQuote(self, index):
text = 'Lorum ipsum ' + str(index)
widget = DragArea(text=text, parent=self, index=index)
item = QListWidgetItem()
item.setFlags(item.flags() &
~Qt.ItemIsSelectable &
~Qt.ItemIsEnabled &
~Qt.ItemIsDragEnabled
)
self.bodyMap[index] = item
item.setSizeHint(
QSize(item.sizeHint().width(), widget.sizeHint().height())
)
self.addItem(item)
self.setItemWidget(item, widget)
def main():
app = QtGui.QApplication(sys.argv)
ex = QuoteArea()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()