Copy/Paste multiple items from QTableView in pyqt4?

后端 未结 3 899
再見小時候
再見小時候 2020-12-18 15:46

We can select multiple items(partial rows and partial columns) from QTableView using self.tableView.setSelectionMode(QAbstractItemView.ExtendedSelection), but a

3条回答
  •  时光说笑
    2020-12-18 16:36

    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())       
    

提交回复
热议问题