Search code examples
qtdrag-and-dropqlistwidget

How to get item index of a thumbnail after drag item from QListWidget Thumbnails?


I will use drag and drop event inside my project. So, now my question is when i dragging an item from QListWidget at that time i want to get index of the thumbnail. I am using this one code for dragging and dropping the thumbnail image.

void QvtkOpenGLWidgetdrag::dragEnterEvent(QDragEnterEvent *event)
{
    QVTKOpenGLWidget::dragEnterEvent(event);
    event->accept();

}

void QvtkOpenGLWidgetdrag::dropEvent(QDropEvent *event)
{
    const QMimeData *mimeData = event->mimeData();
    int row;
    int col;

    if (mimeData->hasFormat("application/x-qabstractitemmodeldatalist")) {
        QByteArray encoded = mimeData->data("application/x-qabstractitemmodeldatalist");
        QDataStream stream(&encoded, QIODevice::ReadOnly);
        while (!stream.atEnd()) {
            QMap<int, QVariant> roleDataMap;
            stream >> row >> col >> roleDataMap ;
            QIcon icon = roleDataMap.value(1).value<QIcon>();
            m_pixmap = icon.pixmap(icon.availableSizes().first());
            update();
        }
        event->acceptProposedAction();
    }
    else {
        event->ignore();
    }
}

Any help is very useful for me. Thank you in advance


Solution

  • you can call the method currentIndex() in the ListWidget, then check if that is valid and if so, get the row value... (note that they begin at 0)

    example

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        ui->listWidget->addItem("A");
        ui->listWidget->addItem("B");
        ui->listWidget->addItem("C");
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }
    
    void MainWindow::on_pushButton_clicked()
    {
    
        auto index = ui->listWidget->currentIndex();
        if (index.isValid())
        {
           std::cout << "row: " << index.row() << std::endl;
        }
    }