My starting point is the following QML source, where GridView is showing ListModel with nice animation of item swaps:
import QtQuick 1.1
GridView {
id: m
I found the solution. Here is the working code (thanks Borut123 for suggestions).
class MyTable : public QStandardItemModel
{
private:
Q_OBJECT
public:
explicit MyTable(QObject *parent = 0) : QStandardItemModel(parent) {}
Q_INVOKABLE void createModel();
Q_INVOKABLE void moveItem(int inx1, int inx2);
Q_INVOKABLE void listItems();
};
void MyTable::createModel()
{
for (unsigned int i=0; i<20; i++) {
QStandardItem* item = new QStandardItem(QString("%1").arg(i));
appendRow(item);
}
}
void MyTable::moveItem(int inx1, int inx2) {
bool ok = false;
if (inx1 < inx2) ok = beginMoveRows(QModelIndex(),inx1,inx1,QModelIndex(),inx2+1);
if (inx1 > inx2) ok = beginMoveRows(QModelIndex(),inx1,inx1,QModelIndex(),inx2);
if (!ok) return;
QStandardItem* tmp1 = takeItem(inx1);
if (inx1<inx2) {
for (int i=inx1; i<inx2; i++) {
QStandardItem* tmp2 = takeItem(i+1);
setItem(i,tmp2);
}
} else if (inx2<inx1) {
for (int i=inx1; i>inx2; i--) {
QStandardItem* tmp2 = takeItem(i-1);
setItem(i,tmp2);
}
}
setItem(inx2,tmp1);
endMoveRows();
}
void MyTable::listItems() {
qDebug() << "LIST OF ITEMS";
for (unsigned int i=0; i<20; i++) {
qDebug() << QString("table[%1]=%2").arg(i).arg(item(i)->text()).toAscii().data();
}
}