Home > Net >  Drag and Drop QTreeWidgetItem to QGraphicsView with custom data
Drag and Drop QTreeWidgetItem to QGraphicsView with custom data

Time:10-26

I've a class containing a QTreeWidget, where I have some QTreeWidgetItem.

I want to drag and drop a QTreeWidgetItem into a QGraphicsScene, in order to create an object in there. The object is a rectangle with the text of the QTreeWidgetItem in there.

I was able to perform the drag and drop operation, and I've my dropEvent virtual method for handling it. It receives the drop event, but I'm not be able to retrieve information about the original QTreeWidgetItem.

This is the code that I've used to initialize the QTreeWidget:

m_nodeList = new QTreeWidget(this);
m_nodeList->setColumnCount(2);
m_nodeList->setHeaderLabels({ NameLabel, CategoryLabel });
m_nodeList->setDragEnabled(true);
m_nodeList->setDragDropMode(QAbstractItemView::DragOnly);

The dropEvent overridden method in my Scene subclass of QGraphicsScene is the following one:

void Scene::dropEvent(QGraphicsSceneDragDropEvent* event) {
  event->acceptProposedAction();

  for (const auto& it : event->mimeData()->formats()) {
    std::string f = it.toStdString();
    int i = 0;
  }
  std::string t = event->mimeData()->text().toStdString();
  std::string on = event->mimeData()->objectName().toStdString();
}

f contains application/x-qabstractitemmodeldatalist, while other strings are empty.

How can I retrieve information about the QTreeWidgetItem that I've dragged into the QGraphicsScene?

CodePudding user response:

DND of models uses an internal Qt format so a possible solution is to use a dummymodel:

void Scene::dropEvent(QGraphicsSceneDragDropEvent* event) {
    event->acceptProposedAction();
    if(event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist")){
        QStandarditemmodel dummy_model;
        if(dummy_model.dropMimeData(event->mimeData(), event->dropAction(), 0, 0, QModelIndex()){
            QModelIndex index = dummy_model.index(0, 0);
            qDebug() << index.data();
        }
    }
}
  • Related