Moving a row to another position
-
Hello,
I have a simple QListView with some text data(QStringListModel) as rows. See attached picture. Can anyone give me an hint how I can move Item3 up to the first position by clicking und pressing the mouse button? I see in the QListView signals pressed and clicked. Don't I need also a signal released.
This should the end result:
Item3
Item1
Item2The source code is here. It is just a dummy application.
-
You can move rows in a QStringListModel with moveRows().
But what exactly do you want to achieve? Moving the rows by a button click or per drag'n'drop? The latter is already possible without extra work on your side. -
@ppp1 said in Moving a row to another position:
I want to move the rows per drag and drop.
Then set dragDropMode of the view to DragDrop and it works.
-
ui->listView->setSelectionMode(QAbstractItemView::SingleSelection); ui->listView->setDragEnabled(true); ui->listView->viewport()->setAcceptDrops(true); ui->listView->setDropIndicatorShown(true); ui->listView->setDragDropMode(QAbstractItemView::InternalMove);
Now it deletes the item at the destination index. I will try later.
-
ui->listView->setSelectionMode(QAbstractItemView::SingleSelection); ui->listView->setDragEnabled(true); ui->listView->viewport()->setAcceptDrops(true); ui->listView->setDropIndicatorShown(true); ui->listView->setDragDropMode(QAbstractItemView::InternalMove); ui->listView->setDragDropOverwriteMode(false);
The selected data overwrites the existing item when dropped. The last command does not work. Any hints?
-
@ppp1 said in Moving a row to another position:
Any hints?
It does work for me with a small testcase in the qt designer with QListWidget. What's not needed is the viewport()->setAcceptDrops() call. What Qt version and Os do you use?
-
Simply create a new widget ui in designer, add a QTreeWidget, add some items, set the flags and do a preview.
-
Found the answer: https://www.walletfox.com/course/qtreorderablelist.php. Variant 2.
Note: The explanation for why we need to override flags() can be found in the documentation of the method bool dragDropOverwriteMode() const. The documentation says that the default behaviour when moving items is items' removal. To prevent the removal of the items it is necessary to reimplement flags() in such way that we do not return Qt::ItemIsDropEnabled.