PDA

View Full Version : Copying QTableView rows



derrickbj
28th September 2006, 00:12
I'm trying to provide copy funcationality in a QTableView so the user can copy an paste rows from the TableView into Excel, for instance. I've got the following set for the TableView (The table has 11 fixed columns, model set as a QAbstractItemModel):

myTableView->setSelectionBehavior(QAbstractItemView::SelectRows );
myTableView->setSelectionMode(QAbstractItemView::ExtendedSelect ion);

The slot that gets called when 'copy' is selected is :

void IOSAnalyzer::copyRows()
{
QString str;


QModelIndexList selectionList = selectionModel->selectedIndexes();
QModelIndex index;

if (selectionList.size() > 0)
{

int k, j = 0;
for (int i=0; i<selectionList.size(); ++i) {

qDebug()<<"row is "<<str.setNum(k)<<"...column is <<"<<str.setNum(selectionList[i].column());
str+=model->index(selectionList[i].row(),selectionList[i].column(),QModelIndex()).data().toString();
str+="\t";
}
}
QApplication::clipboard()->setText(str);
}

Naturally, this doesn't work, but the funny part is - if I select rows 5-7, qDebug() shows :

row is 5...column is 0
row is 6...column is 0
row is 7...column is 0
row is 5...column is 1
row is 6...column is 1
row is 7...column is 1
..and so on.

Now, if I hold down the control key and select row 5, then 7, then 6 and hit 'copy', qDebug shows:

row is 5...column is 0
through
row is 5...column is 10
row is 7...column is 0
through
row is 7...column is 10
row is 6...column is 0
through
row is 6...column is 10

These two results into the QModelIndexList make it difficult to add lines into QString str. If I select all rows, and interate as follows:

for (int i = 0; i < totalRows; ++i)
{
for (int x=0; x<11; ++x)
{
str+=model->index(i,x,QModelIndex()).data().toString();
str+="\t";
}
str += "\n";
}

This works like a charm... but not for holding down the control key, or selecting a smaller range of rows.

Is there an easier way??? Every example I can find either only copies a single cell, or doesn't even copy it to the clipboard.

Thanks,
--D

wysota
28th September 2006, 01:00
First of all use "the proper way" of dealing with copy/paste which is using QAbstractItemModel::mimeData(). As for the problem with ordered items, either just reorder the items or find the minimum and maximum values for row/column and encode the range of items they hold. The first idea will work properly with multiple selections, but the second one should be easier/faster (and will work for extended selection as well).