QAbstractItemModel::index()
To copy to clipboard, switch view to plain text mode
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:
};
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;
};
To copy to clipboard, switch view to plain text mode
Bookmarks