[Qt-interest] Trouble making ListView accepting drops

Nathan Hüsken nathan.huesken at posteo.de
Wed Oct 5 13:19:04 CEST 2011


Hi,

I have two list views. The first (ImageList) is a list of images, the
second (ReferencesList) is a list of references to these images. The
first has the model ImageListModel, the second the model
ReferencesListModel.

Now I want to enable drag and drop, dragging images from the first
listview to the second to create a new reference.

In the constructor of the main window I do this to enable drag and drop:

imageList->setDragEnabled(true);
referencesList->setAcceptDrops(true);
referencesList->setDropIndicatorShown(true);

Also, I added the code, listed below, to enable drag and drop for the lists.
Now, dragging an element from the imageList works, but when I drag it
over the referencesList, the icon indicates I can not drop it here.

What am I missing?
Thanks!

This is the relevant code I added to the models:
-------------------------- ImageListModel.cpp------------------------
Qt::DropActions ImageListModel::supportedDragActions() const {
  return Qt::CopyAction;
}

const QPixmap ImageListModel::getThumbnail(const QString& name) const {
  return m_images.find(name)->second.m_thumbnail;
}

Qt::ItemFlags ImageListModel::flags(const QModelIndex& index) const {
   Qt::ItemFlags defaultFlags = QAbstractListModel::flags(index);
   if (index.isValid())
     return Qt::ItemIsDragEnabled | defaultFlags;
   else
     return defaultFlags;
}

QStringList ImageListModel::mimeTypes() const
{
  QStringList types;
  types << "application/image.name";
  return types;
}

QMimeData *ImageListModel::mimeData(const QModelIndexList &indexes) const {
     QMimeData *mimeData = new QMimeData();
     QByteArray encodedData;

     QDataStream stream(&encodedData, QIODevice::WriteOnly);

     foreach (QModelIndex index, indexes) {
         if (index.isValid()) {
             QString text = m_imageNames[index.row()]; // Image name
contains the names of the images and is supposed to be used for reference
             stream << text;
         }
     }
     mimeData->setData("application/image.name", encodedData);
     return mimeData;
 }

----------------------------ReferecesListModel.cpp---------------------
QStringList ReferencesListModel::mimeTypes() const {
  QStringList types;
  types << "application/image.name";
   return types;
}

Qt::DropActions ReferencesListModel::supportedDropActions() const {
  return Qt::CopyAction;
}

bool ReferencesListModel::dropMimeData(const QMimeData *data,
Qt::DropAction action, int row, int column, const QModelIndex &parent) {
  // Not implemented yet
  return true;
}



More information about the Qt-interest-old mailing list