【问题标题】:How to Copy and Paste multiple rows/columns in QTableView (data sources from pandas dataframe)? [duplicate]如何在 QTableView 中复制和粘贴多行/列(来自 pandas 数据框的数据源)? [复制]
【发布时间】:2021-09-15 17:35:33
【问题描述】:

我在 GUI 中使用Pyqt5 中的QTableView 显示数据框。我应该如何对其进行编码,以便用户可以同时复制粘贴多行/列以及行索引(用于行)和标题(用于列)?

我在下面举了一个简单的例子。我假设我们需要一个QTableView 的子类并为它定义一个keyPressEvent

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import Qt
import pandas as pd

class TableModel(QtCore.QAbstractTableModel):

    def __init__(self, data):
        super(TableModel, self).__init__()
        self._data = data

    def data(self, index, role):
        if role == Qt.DisplayRole:
            value = self._data.iloc[index.row(), index.column()]
            return str(value)

    def rowCount(self, index):
        return self._data.shape[0]

    def columnCount(self, index):
        return self._data.shape[1]

    def headerData(self, section, orientation, role):
        # section is the index of the column/row.
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                return str(self._data.columns[section])

            if orientation == Qt.Vertical:
                return str(self._data.index[section])

class View(QTableView):
    def __init__(self):
        super(View, self).__init__(parent=None)

    def keyPressEvent(self, event):
        if event.matches(QKeySequence.Copy):
            # some code to get copy_text?  
            QApplication.clipboard().setText(copy_text)


        QTableView.keyPressEvent(self, event)

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self):
        super().__init__()

        self.table = View() # use subclass View() instead of self.table = QtWidgets.QTableView()

        data = pd.DataFrame([
          [1, 9, 2],
          [1, 0, -1],
          [3, 5, 2],
          [3, 3, 2],
          [5, 8, 9],
        ], columns = ['A', 'B', 'C'], index=['Row 1', 'Row 2', 'Row 3', 'Row 4', 'Row 5'])

        self.model = TableModel(data)
        self.table.setModel(self.model)
        self.setCentralWidget(self.table)


app=QtWidgets.QApplication(sys.argv)
window=MainWindow()
window.show()
app.exec_()

【问题讨论】:

    标签: python dataframe user-interface pyqt5 qtableview


    【解决方案1】:

    您可以循环查看selectedIndexes(),然后最终对它们进行排序。

    def keyPressEvent(self, event):
        if event.matches(QtGui.QKeySequence.Copy):
            data = []
            for index in sorted(self.selectedIndexes()):
                data.append(('{}\t\t{}\t\t{}'.format(
                    index.row(), index.column(), index.data())))
            if data:
                QtWidgets.QApplication.clipboard().setText(
                    'Row\t\tCol\t\tValue:\n' + '\n'.join(data))
                return
        QtWidgets.QTableView.keyPressEvent(self, event)
    

    请注意,默认的 QModelIndex 实现支持先按行排序,然后按列排序,但您可以使用 lambda 更改行为:

    for index in sorted(self.selectedIndexes(), key=lambda i: (i.column(), i.row())):
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      相关资源
      最近更新 更多