Selected Rows in QTableView, copy to QClipboard

后端 未结 12 616
别那么骄傲
别那么骄傲 2020-12-25 08:14

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

12条回答
  •  轮回少年
    2020-12-25 08:49

    Here is a variation on what Corwin Joy posted that works with QTableView and handles sparse selections differently. With this code if you have different columns selected in different rows (e.g. selected cells are (1,1), (1, 2), (2, 1), (3,2)) then when you paste it you will get empty cells corresponding to the "holes" in your selection (e.g. cells (2,2) and (3,1)). It also pulls in the column header text for columns that intersect the selection.

    void CopyableTableView::copy()
    {
        QItemSelectionModel *selection = selectionModel();
        QModelIndexList indices = selection->selectedIndexes();
    
        if(indices.isEmpty())
            return;
    
        QMap selectedColumnsMap;
        foreach (QModelIndex current, indices) {
            selectedColumnsMap[current.column()] = true;
        }
        QList selectedColumns = selectedColumnsMap.uniqueKeys();
        int minCol = selectedColumns.first();
    
        // prepend headers for selected columns
        QString selectedText;
    
        foreach (int column, selectedColumns) {
            selectedText += model()->headerData(column, Qt::Horizontal, Qt::DisplayRole).toString();
            if (column != selectedColumns.last())
                selectedText += QLatin1Char('\t');
        }
        selectedText += QLatin1Char('\n');
    
        // QModelIndex::operator < sorts first by row, then by column.
        // this is what we need
        qSort(indices);
    
        int lastRow = indices.first().row();
        int lastColumn = minCol;
    
        foreach (QModelIndex current, indices) {
    
            if (current.row() != lastRow) {
                selectedText += QLatin1Char('\n');
                lastColumn = minCol;
                lastRow = current.row();
            }
    
            if (current.column() != lastColumn) {
                for (int i = 0; i < current.column() - lastColumn; ++i)
                    selectedText += QLatin1Char('\t');
                lastColumn = current.column();
            }
    
            selectedText += model()->data(current).toString();
        }
    
        selectedText += QLatin1Char('\n');
    
        QApplication::clipboard()->setText(selectedText);
    }
    

提交回复
热议问题