PDA

View Full Version : Copy selected rows of a table to a model



panoss
23rd February 2017, 09:39
I want to make a new model containing only the selected rows of this table.
Appending the selected rows to the empty model named "selected_rows_model" (QSqlTableModel).


QItemSelectionModel *selectionModel = ui.devices_finder_tbl->selectionModel();
if(selectionModel->hasSelection() ){
//QModelIndexList list = selectionModel->selectedRows();
QModelIndexList list = ui.devices_finder_tbl->selectedIndexes();
for(int i = 0; i < list.size(); i++)
{
QModelIndex index = list.at(i);
selected_rows_model->insertRow(selected_rows_model->rowCount(), index);
}
}

But it's not working, this row:


selected_rows_model->insertRow(selected_rows_model->rowCount(), index);

is wrong.
Ho can I fix it?

Santosh Reddy
23rd February 2017, 10:17
QModelIndex is specific to the model, it cannot be copied/supplied to another model. You will have to create another new QModelIndex for the selected_rows_model.

panoss
23rd February 2017, 10:25
How can I do this? Can you give me an example?

Santosh Reddy
23rd February 2017, 12:03
You can create a new QModelIndex using
QAbstractItemModel::index()

Here is a working example.


class SelectionCopier : public QObject
{
Q_OBJECT
public:
explicit SelectionCopier(const QAbstractItemView * from, QAbstractItemView * to, QObject * parent = 0)
: QObject(parent)
, mFromTable(from)
, mToTable(to)
{
mToTable->setModel(new QStandardItemModel(mToTable));

connect(from, SIGNAL(pressed(QModelIndex)), SLOT(copySelection()));
}

protected slots:
void copySelection()
{
const QAbstractItemModel * fromModel = mFromTable->model();
QAbstractItemModel * toModel = mToTable->model();

toModel->removeRows(0, toModel->rowCount());
toModel->removeColumns(0, toModel->columnCount());

QItemSelectionModel * selectionModel = mFromTable->selectionModel();

if(selectionModel->hasSelection())
{
toModel->insertColumns(0, fromModel->columnCount());

QList<int> rows;

foreach(const QModelIndex & modelIndex, selectionModel->selectedIndexes())
{
if(!rows.contains(modelIndex.row()))
{
rows.append(modelIndex.row());
toModel->insertRow(toModel->rowCount());
}

const int row = rows.indexOf(modelIndex.row());
const int col = modelIndex.column();

const QModelIndex index = toModel->index(row, col);

for(int role = 0; role < Qt::UserRole; ++role)
toModel->setData(index, modelIndex.data(role), role);
}
}
}

private:
const QAbstractItemView * const mFromTable;
QAbstractItemView * const mToTable;
};