Copy/Paste multiple items from QTableView in pyqt4?

copy-paste, pyqt4, python, qabstractitemview, qtableview

Solution

self.tableView.installEventFilters(self)

Now, adding event filter:

def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.KeyPress and
            event.matches(QtGui.QKeySequence.Copy)):
            self.copySelection()
            return True
        return super(Window, self).eventFilter(source, event)

Copy Function:

def copySelection(self):
        selection = self.tableView.selectedIndexes()
        if selection:
            rows = sorted(index.row() for index in selection)
            columns = sorted(index.column() for index in selection)
            rowcount = rows[-1] - rows[0] + 1
            colcount = columns[-1] - columns[0] + 1
            table = [[''] * colcount for _ in range(rowcount)]
            for index in selection:
                row = index.row() - rows[0]
                column = index.column() - columns[0]
                table[row][column] = index.data()
            stream = io.StringIO()
            csv.writer(stream).writerows(table)
            QtGui.qApp.clipboard().setText(stream.getvalue())       

Problem

We can select multiple items(partial rows and partial columns) from QTableView using `self.tableView.setSelectionMode(QAbstractItemView.ExtendedSelection)`, but after selecting some rows and columns(partial and partial) if I do CTRL+C and paste it in notepad it only pastes one item(one value from the tableView)? My Code: ``` tab_table_view = QtGui.QWidget() self.Tab.insertTab(0, tab_table_view, self.File_Name) self.tableView = QtGui.QTableView(tab_table_view) self.tableView.setGeometry(QtCore.QRect(0, 0, 721, 571)) self.model = QtGui.QStandardItemModel(self) self.model.setSortRole(QtCore.Qt.UserRole) self.tableView.setModel(self.model) self.tableView.setSelectionMode(QAbstractItemView.ExtendedSelection) '''this helps for selecting multiple items but not able to copy and paste multiple values to a text/ excel (it only copies single value)''' ``` How can we do copy and paste multiple items?

Original source