As shown in the image on the left side i have a QListWidget named "my_listwidget" populated with 3 commands and on the right side i have a QPlainTextEdit named "my_textedit".
i am able to drag from QListWidget by using this code
ui->block_commands_listwidget->setSelectionMode(QAbstractItemView::SingleSelection);
ui->block_commands_listwidget->setDragEnabled(true);
ui->block_commands_listwidget ->setDragDropMode(QAbstractItemView::DragDrop);
ui->block_commands_listwidget->viewport()->setAcceptDrops(false);
ui->block_commands_listwidget->setDropIndicatorShown(true);
But i am not able to drop into my QPlainTextEdit, i guess because when i drag, its of "item type" and when im trying to drop into textbox, the QPlainTextEdit accepts only Text but not item type. How do i do this ? Thanks for going through this.
The problem is simple: QPlaintTextEdit does not recognize the mimetype that the QListWidget sends by default, so the solution is to override the mimeData()
method adding the text of the selected items as plain text:
#include <QtWidgets>
class ListWidget: public QListWidget{
public:
using QListWidget::QListWidget;
protected:
QMimeData *mimeData(const QList<QListWidgetItem *> items) const
{
QMimeData *md = QListWidget::mimeData(items);
QStringList texts;
for(QListWidgetItem *item : selectedItems())
texts << item->text();
md->setText(texts.join(QStringLiteral("\n")));
return md;
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QWidget w;
ListWidget *lw = new ListWidget;
lw->addItems({"First Command", "Second Command", "Third Command"});
lw->setSelectionMode(QAbstractItemView::SingleSelection);
lw->setDragEnabled(true);
lw->setDragDropMode(QAbstractItemView::DragOnly);
QPlainTextEdit *pe = new QPlainTextEdit;
QHBoxLayout *lay = new QHBoxLayout(&w);
lay->addWidget(lw);
lay->addWidget(pe);
w.show();
return a.exec();
}