Question

I have a listwidget and a treewidget. I want the listwidgetitems to be able to move inside the listwidget via drag and drop, and I also want the listwidget to accept drops from dragged items from the treewidget, but, prior to this, I want to do some processing to the data.

I can do all of these things right now, but I am unable to find out how to set custom data to the drag event starting from the treewidget.

For example, I have a topLevelItem in my treewidget with the text "Add DrawEffect" and with a QIcon as well, which, when I drag and drop inside the listwidget, I want to add a new item to the listwidget, saying:

DrawEffect 0x0x0x0 effect-here

and not

Add DrawEffect (showing its QIcon as well)

WHEN should I set this data?

This is my code so far that works completely fine when dragging and dropping listwidgetitems inside the listwidget, and it works for drag and dropping qtreewidgetitems inside the listwidget, but it copies them as are, while I want to do further processing prior to adding them:

At my treewidget's constructor:

this->setDragDropMode(QAbstractItemView::DragOnly);
this->setDefaultDropAction(Qt::CopyAction);

At my listwidget's constructor:

this->setAcceptDrops(true);
this->setDragDropMode(QAbstractItemView::DragDrop);
this->setDefaultDropAction(Qt::MoveAction);

re-implementing listwidget's dropEvent:

if(event->source()->inherits("QTreeWidget"))
    qDebug() << "The dragged item comes from the TreeWidget.";
else
    qDebug() << "The dragged item comes from the ListWidget itself.";
QListWidget::dropEvent(event);

As you can see I can distinguish between the treewidget and the listwidget items but I don't know what to do after this...

I guess that something like this would be OK:

if(event->source()->inherits("QTreeWidget")){
    //treewidget item, it needs further processing
}
else
    QListWidget::dropEvent(event); //listwidget item, no further processing needed

Thanks :/

Was it helpful?

Solution

To answer, as cmannett85 said, when entering drag, automatically mime data will be added to the drag event. You can override what mimedata is added by overriding QTableWidget::mimeData(). In this method, you can set some identifier for the item at that position (for eg: row no, col no, index into some data structure )

Then, override dropMimedata method in the list widget to read this data added by you and perform the insert operation

See, When dragging a row in a QTableWidget, how can I find out what row index it was dragged FROM and TO? for more detail

OTHER TIPS

AFAIK the drag operation does not 'contain' the item, it just contains the data that describes it. So you would need create a new item from the text, icon, etc. data from the event->mimeData() object and manually insert it into your widget at event->pos().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top