Selected Rows in QTableView, copy to QClipboard

35,802

Solution 1

To actually capture the selection you use the item view's selection model to get a list of indices. Given that you have a QTableView * called view you get the selection this way:

QAbstractItemModel * model = view->model();
QItemSelectionModel * selection = view->selectionModel();
QModelIndexList indexes = selection->selectedIndexes();

Then loop through the index list calling model->data(index) on each index. Convert the data to a string if it isn't already and concatenate each string together. Then you can use QClipboard.setText to paste the result to the clipboard. Note that, for Excel and Calc, each column is separated from the next by a newline ("\n") and each row is separated by a tab ("\t"). You have to check the indices to determine when you move to the next row.

QString selected_text;
// You need a pair of indexes to find the row changes
QModelIndex previous = indexes.first();
indexes.removeFirst();
foreach(const QModelIndex &current, indexes)
{
    QVariant data = model->data(current);
    QString text = data.toString();
    // At this point `text` contains the text in one cell
    selected_text.append(text);
    // If you are at the start of the row the row number of the previous index
    // isn't the same.  Text is followed by a row separator, which is a newline.
    if (current.row() != previous.row())
    {
        selected_text.append('\n');
    }
    // Otherwise it's the same row, so append a column separator, which is a tab.
    else
    {
        selected_text.append('\t');
    }
    previous = current;
}
QApplication.clipboard().setText(selected_text);

Warning: I have not had a chance to try this code, but a PyQt equivalent works.

Solution 2

I had a similar problem and ended up adapting QTableWidget (which is an extension of QTableView) to add copy/paste functionality. Here is the code which builds on what was provided by quark above:

qtablewidgetwithcopypaste.h

// QTableWidget with support for copy and paste added
// Here copy and paste can copy/paste the entire grid of cells
#ifndef QTABLEWIDGETWITHCOPYPASTE_H
#define QTABLEWIDGETWITHCOPYPASTE_H

#include <QTableWidget>
#include <QKeyEvent>
#include <QWidget>

class QTableWidgetWithCopyPaste : public QTableWidget
{
    Q_OBJECT
public:
  QTableWidgetWithCopyPaste(int rows, int columns, QWidget *parent = 0) :
      QTableWidget(rows, columns, parent)
  {}

  QTableWidgetWithCopyPaste(QWidget *parent = 0) :
  QTableWidget(parent)
  {}

private:
  void copy();
  void paste();

public slots:
  void keyPressEvent(QKeyEvent * event);
};

#endif // QTABLEWIDGETWITHCOPYPASTE_H

qtablewidgetwithcopypaste.cpp

#include "qtablewidgetwithcopypaste.h"
#include <QApplication>
#include <QMessageBox>
#include <QClipboard>
#include <QMimeData>

void QTableWidgetWithCopyPaste::copy()
{
    QItemSelectionModel * selection = selectionModel();
    QModelIndexList indexes = selection->selectedIndexes();

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

    // QModelIndex::operator < sorts first by row, then by column.
    // this is what we need
//    std::sort(indexes.begin(), indexes.end());
    qSort(indexes);

    // You need a pair of indexes to find the row changes
    QModelIndex previous = indexes.first();
    indexes.removeFirst();
    QString selected_text_as_html;
    QString selected_text;
    selected_text_as_html.prepend("<html><style>br{mso-data-placement:same-cell;}</style><table><tr><td>");
    QModelIndex current;
    Q_FOREACH(current, indexes)
    {
        QVariant data = model()->data(previous);
        QString text = data.toString();
        selected_text.append(text);
        text.replace("\n","<br>");
        // At this point `text` contains the text in one cell
        selected_text_as_html.append(text);

        // If you are at the start of the row the row number of the previous index
        // isn't the same.  Text is followed by a row separator, which is a newline.
        if (current.row() != previous.row())
        {
            selected_text_as_html.append("</td></tr><tr><td>");
            selected_text.append(QLatin1Char('\n'));
        }
        // Otherwise it's the same row, so append a column separator, which is a tab.
        else
        {
            selected_text_as_html.append("</td><td>");
            selected_text.append(QLatin1Char('\t'));
        }
        previous = current;
    }

    // add last element
    selected_text_as_html.append(model()->data(current).toString());
    selected_text.append(model()->data(current).toString());
    selected_text_as_html.append("</td></tr>");
    QMimeData * md = new QMimeData;
    md->setHtml(selected_text_as_html);
//    qApp->clipboard()->setText(selected_text);
    md->setText(selected_text);
    qApp->clipboard()->setMimeData(md);

//    selected_text.append(QLatin1Char('\n'));
//    qApp->clipboard()->setText(selected_text);
}

void QTableWidgetWithCopyPaste::paste()
{
    if(qApp->clipboard()->mimeData()->hasHtml())
    {
        // TODO, parse the html data
    }
    else
    {
        QString selected_text = qApp->clipboard()->text();
        QStringList cells = selected_text.split(QRegExp(QLatin1String("\\n|\\t")));
        while(!cells.empty() && cells.back().size() == 0)
        {
            cells.pop_back(); // strip empty trailing tokens
        }
        int rows = selected_text.count(QLatin1Char('\n'));
        int cols = cells.size() / rows;
        if(cells.size() % rows != 0)
        {
            // error, uneven number of columns, probably bad data
            QMessageBox::critical(this, tr("Error"),
                                  tr("Invalid clipboard data, unable to perform paste operation."));
            return;
        }

        if(cols != columnCount())
        {
            // error, clipboard does not match current number of columns
            QMessageBox::critical(this, tr("Error"),
                                  tr("Invalid clipboard data, incorrect number of columns."));
            return;
        }

        // don't clear the grid, we want to keep any existing headers
        setRowCount(rows);
        // setColumnCount(cols);
        int cell = 0;
        for(int row=0; row < rows; ++row)
        {
            for(int col=0; col < cols; ++col, ++cell)
            {
                QTableWidgetItem *newItem = new QTableWidgetItem(cells[cell]);
                setItem(row, col, newItem);
            }
        }
    }
}

void QTableWidgetWithCopyPaste::keyPressEvent(QKeyEvent * event)
{
    if(event->matches(QKeySequence::Copy) )
    {
        copy();
    }
    else if(event->matches(QKeySequence::Paste) )
    {
        paste();
    }
    else
    {
        QTableWidget::keyPressEvent(event);
    }

}

Solution 3

Quark's answer (the selected one) is good for pointing people in the right direction, but his algorithm is entirely incorrect. In addition to an off by one error and incorrect assignment, its not even syntactically correct. Below is a working version that I just wrote and tested.

Let's assume our example table looks like so:

A | B | C
D | E | F

The problem with Quark's algorithm is the following:

If we replace his \t separator with a ' | ', it will produce this output:
B | C | D
E | F |

The off by one error is that D appears in the first row. The incorrect assignment is evidenced by the omission of A

The following algorithm corrects these two problems with correct syntax.

    QString clipboardString;
    QModelIndexList selectedIndexes = view->selectionModel()->selectedIndexes();

    for (int i = 0; i < selectedIndexes.count(); ++i)
    {
        QModelIndex current = selectedIndexes[i];
        QString displayText = current.data(Qt::DisplayRole).toString();

        // If there exists another column beyond this one.
        if (i + 1 < selectedIndexes.count())
        {
            QModelIndex next = selectedIndexes[i+1];

            // If the column is on different row, the clipboard should take note.
            if (next.row() != current.row())
            {
                displayText.append("\n");
            }
            else
            {
                // Otherwise append a column separator.
                displayText.append(" | ");
            }
        }
        clipboardString.append(displayText);
    }

    QApplication::clipboard()->setText(clipboardString);

The reason I chose to use a counter instead of an iterator is just because it is easier to test if there exists another index by checking against the count. With an iterator, I suppose maybe you could just increment it and store it in a weak pointer to test if it is valid but just use a counter like I did above.

We need to check if the next line will be on on a new row. If we are on a new row and we check the previous row as Quark's algorithm does, its already too late to append. We could prepend, but then we have to keep track of the last string size. The above code will produce the following output from the example table:

A | B | C
D | E | F

Solution 4

For whatever reason I didn't have access to the std::sort function, however I did find that as a neat alternative to Corwin Joy's solution, the sort function can be implemented by replacing

 std::sort(indexes.begin(), indexes.end());

with

  qSort(indexes);

This is the same as writing:

 qSort(indexes.begin(), indexes.end());

Thanks for your helpful code guys!

Solution 5

What you'll need to do is access the text data in the model, then pass that text to the QClipboard.

To access the text data in the model, use QModelIndex::data(). The default argument is Qt::DisplayRole, i.e. the displayed text.

Once you've retrieved the text, pass that text to the clipboard using QClipboard::setText().

Share:
35,802
Berschi
Author by

Berschi

Updated on February 19, 2020

Comments

  • Berschi
    Berschi over 4 years

    I have a SQLite-Database and I did it into a QSqlTableModel. To show the Database, I put that Model into a QTableView.

    Now I want to create a Method where the selected Rows (or the whole Line) will be copied into the QClipboard. After that I want to insert it into my OpenOffice.Calc-Document.

    But I have no Idea what to do with the Selected SIGNAL and the QModelIndex and how to put this into the Clipboard.

  • Berschi
    Berschi almost 15 years
    thank you, it really helped, for now. I added following code: connect (tableView, SIGNAL(clicked(QModelIndex)), this, SLOT(copy(QModelIndex))); and this: void Widget::copy(QModelIndex sel) { clipboard->setText((sel.data(Qt::DisplayRole)).toString()); } this works fine for one single Row. But if I select 2 or more rows, this doesn't work. How can I copy more rows or a whole line to the Clipboard?
  • Berschi
    Berschi almost 15 years
    oh sorry, I'm really new here... and with row (comment above) I meant cell. sorry :(
  • Berschi
    Berschi almost 15 years
    sorry, but I don't get it how to use QItemSelectionModel and QModelIndexList in this case with the Model and TableView
  • swongu
    swongu almost 15 years
    Because you're using clicked(QModelIndex), this will only return the cell the user clicked on. If you want to copy text from all selected cells, you'd use the solution quark proposed. BTW, you should add your code snippets as updates to your original question.
  • swongu
    swongu almost 15 years
    Here, you can also use the convenient function QAbstractItemView::selectedIndexes() that is available on your QTableView (in which QAbstractItemView is a parent of). What's returned is a simple list container of QModelIndex objects.
  • quark
    quark almost 15 years
    I've expanded a little on the example to illustrate what swongu describes.
  • Berschi
    Berschi almost 15 years
    thank you very much, I also got a (not so nice) solution, but it works.
  • swongu
    swongu almost 15 years
    If you use a QStringList, you can take advantage of the << operator and the QStringList::join() function.
  • Corwin Joy
    Corwin Joy over 14 years
    thank you for the above, this was very helpful. I did encounter a couple bugs with the above. 1. The cells need to be sorted in row ascending order std::sort(indexes.begin(), indexes.end()); 2. The first cell gets left out in the above logic. It should read <code> foreach{ QVariant data = model()->data(previous); ... } // add last element selected_text.append(model()->data(current).toString()); selected_text.append(QLatin1Char('\n')); </code>
  • phyatt
    phyatt over 9 years
    Two more links that may be helpful are books.google.com/… and stackoverflow.com/a/12979530/999943 and
  • Josh Sanders
    Josh Sanders about 9 years
    This solution is incorrect. It has an off by one error, an incorrect assignment error, and several syntactical errors. Please see my answer for a correct algorithm.
  • Joachim W
    Joachim W over 4 years
    Also be warned that the list returned by QItemSelectionModel::selectedIndexes() is not sorted.