Moving items between models
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
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:
Code:
void moveToRight() {
leftListView->setUpdatesEnabled(false);
rightListView->setUpdatesEnabled(false);
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++) {
//rightModel->insertRow(indexes.at(i).row());
// 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) {
leftModel->removeRow(0);
}
leftListView->setUpdatesEnabled(true);
rightListView->setUpdatesEnabled(true);
}
I do not yet know of a way to add the items to the other model. Also, the removing doesn't seem to work.
Re: Moving items between models
This code works fine
Code:
void Widget::on_moveRightButton_clicked()
{
QModelIndexList leftSelection = ui->leftView->selectionModel ()->selectedIndexes ();
int rowCount;
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;
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 ());
}
}
Re: Moving items between models
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).