View Full Version : Moving items between models

1st July 2011, 14:00
I am trying to make a dialog with two lists, where items can be moved between each list, like so:

http://img40.imageshack.us/img40/1722/dialogh.th.png (http://imageshack.us/photo/my-images/40/dialogh.png/)

I am using a QListView and QStringListModel. How can i move the selected items from one list model to the other?

This is what i have got so far:

void moveToRight() {
QStringListModel* leftModel = (QStringListModel*)leftListView->model();
QStringListModel* rightModel = (QStringListModel*)rightListView->model();


QModelIndexList indexes = leftListView->selectionModel()->selectedIndexes();
qSort(indexes.begin(), indexes.end());

// Add the selected items to the right list
for (int i = 0; i < indexes.count(); i++) {
// I'm guessing i could get the QStringList from the model
// and add to that.

// Then remove them from the left list
for (int i = indexes.count() - 1; i > -1; --i) {


I do not yet know of a way to add the items to the other model. Also, the removing doesn't seem to work.

1st July 2011, 15:10
This code works fine

void Widget::on_moveRightButton_clicked()
QModelIndexList leftSelection = ui->leftView->selectionModel ()->selectedIndexes ();

int rowCount;
Q_FOREACH (QModelIndex idx, leftSelection) {
rowCount = m_rightModel.rowCount ();
m_rightModel.insertRow (rowCount);

m_rightModel.setData (m_rightModel.index (rowCount), idx.data ());

for (int i = leftSelection.size (); i > 0; --i) {
m_leftModel.removeRow (leftSelection.at (i - 1).row ());

void Widget::on_moveLeftButton_clicked()
QModelIndexList rightSelection = ui->rightView->selectionModel ()->selectedIndexes ();

int rowCount;
Q_FOREACH (QModelIndex idx, rightSelection) {
rowCount = m_leftModel.rowCount ();
m_leftModel.insertRow (rowCount);

m_leftModel.setData (m_leftModel.index (rowCount), idx.data ());

for (int i = rightSelection.size (); i > 0; --i) {
m_rightModel.removeRow (rightSelection.at (i - 1).row ());

2nd July 2011, 14:39
Yeah, that worked. Thanks.

I suppose i could have figured it out myself, i just though i'd ask in-case there was a better way. Btw, in your example, you didn't sort the indexes. I think this is necessary in order to remove them from the model without invalidating the indexes (at least, that's what i heard).