Qt drag and drop between two QListWidget

老子叫甜甜 提交于 2019-12-12 09:36:49

问题


I've two QListWidget (list1 and list2)

  • list1 should be able to receive items from list2
  • list1 should be able to be reorganized with an internal drag and drop
  • list2 should be able to receive items from list1

list1->setSelectionMode(QAbstractItemView::SingleSelection);
list1->setDragEnabled(true);
list1->setDragDropMode(QAbstractItemView::DragDrop);
list1->viewport()->setAcceptDrops(true);
list1->setDropIndicatorShown(true);

ulist2->setSelectionMode(QAbstractItemView::SingleSelection);
list2->setDragEnabled(true);
list2->setDragDropMode(QAbstractItemView::InternalMove);
list2->viewport()->setAcceptDrops(true);
list2->setDropIndicatorShown(true);

I had to put the list2 on InternalMove otherwise the item is not remove when I drag it to the list1.

And if i put list1 to InternalMove i can't drop any more on it.

Do I have to write my own drag and drop function to do that?


回答1:


You can extend QListWidget overriding dragMoveEvent method like below

#ifndef MYLISTWIDGET_HPP
#define MYLISTWIDGET_HPP

#include <QListWidget>

class MyListWidget : public QListWidget {

public:
    MyListWidget(QWidget * parent) :
        QListWidget(parent) {}

protected:
    void dragMoveEvent(QDragMoveEvent *e) {
        if (e->source() != this) {
            e->accept();
        } else {
            e->ignore();
        }
    }
};

#endif // MYLISTWIDGET_HPP

Inside our implementation we check the source of the drag event and we don't accept (allow) dropping items that come from our widget itself.
If you're using QtDesigner you can use Promote to... option from the context menu when you right click on the QListWidget on your form. You have to enter a name of your new class (MyListWidget in my example) and you have to enter a name of new header file, where your class will be declared (you can copy and paste the code above into this file).



来源:https://stackoverflow.com/questions/4591923/qt-drag-and-drop-between-two-qlistwidget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!