Copying part of QTableView

Well, already figured it out, sorry anyone that wasted their time and looked.

void TestCopyTable::on_pushButton_copy_clicked()
{
QAbstractItemModel *abmodel = ui.tableView->model();
QItemSelectionModel * model = ui.tableView->selectionModel();
QModelIndexList list = model->selectedIndexes();

qSort(list);

if(list.size() < 1)
    return;

QString copy_table;
QModelIndex last = list.last();
QModelIndex previous = list.first();

list.removeFirst();

for(int i = 0; i < list.size(); i++)
{
    QVariant data = abmodel->data(previous);
    QString text = data.toString();

    QModelIndex index = list.at(i);
    copy_table.append(text);

    if(index.row() != previous.row())

    {
        copy_table.append('\n');
    }
    else
    {
        copy_table.append('\t');
    }
    previous = index;
}

copy_table.append(abmodel->data(list.last()).toString());
copy_table.append('\n');

QClipboard *clipboard = QApplication::clipboard();
clipboard->setText(copy_table);

}


I wrote some code based on Phil's to copy the selection when the user types Control-C.

I subclassed QTableWidget and overrode keyPressEvent():

void MyTableWidget::keyPressEvent(QKeyEvent* event) {
    // If Ctrl-C typed
    // Or use event->matches(QKeySequence::Copy)
    if (event->key() == Qt::Key_C && (event->modifiers() & Qt::ControlModifier))
    {
        QModelIndexList cells = selectedIndexes();
        qSort(cells); // Necessary, otherwise they are in column order

        QString text;
        int currentRow = 0; // To determine when to insert newlines
        foreach (const QModelIndex& cell, cells) {
            if (text.length() == 0) {
                // First item
            } else if (cell.row() != currentRow) {
                // New row
                text += '\n';
            } else {
                // Next cell
                text += '\t';
            }
            currentRow = cell.row();
            text += cell.data().toString();
        }

        QApplication::clipboard()->setText(text);
    }
}

Output example (tab-separated):

foo bar baz qux
bar baz qux foo
baz qux foo bar
qux foo bar baz