Copy selected rows of a table to a model
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).
Code:
if(selectionModel->hasSelection() ){
//QModelIndexList list = selectionModel->selectedRows();
QModelIndexList list = ui.devices_finder_tbl->selectedIndexes();
for(int i = 0; i < list.size(); i++)
{
selected_rows_model->insertRow(selected_rows_model->rowCount(), index);
}
}
But it's not working, this row:
Code:
selected_rows_model->insertRow(selected_rows_model->rowCount(), index);
is wrong.
Ho can I fix it?
Re: Copy selected rows of a table to a model
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.
Re: Copy selected rows of a table to a model
How can I do this? Can you give me an example?
Re: Copy selected rows of a table to a model
You can create a new QModelIndex using
Here is a working example.
Code:
class SelectionCopier
: public QObject{
Q_OBJECT
public:
, mFromTable(from)
, mToTable(to)
{
connect(from,
SIGNAL(pressed
(QModelIndex)),
SLOT(copySelection
()));
}
protected slots:
void copySelection()
{
toModel->removeRows(0, toModel->rowCount());
toModel->removeColumns(0, toModel->columnCount());
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();
for(int role = 0; role < Qt::UserRole; ++role)
toModel->setData(index, modelIndex.data(role), role);
}
}
}
private:
};