将行从一个 table 复制到另一个

Copy a row from one table to another

我想将 table 的整行复制到另一个 table,但每次我调用此函数时,它都会在 t2(table 2) 上添加一个空行 为什么这段代码没有返回任何值

尝试

def _copyRow(self):
    self.t2.insertRow(self.t2.rowCount())   
    columnCount = self.t1.columnCount()  
    for j in range(columnCount):
        if not self.t1.item(rowCount - 2, j) is None:
            self.t1.setItem(rowCount - 1, j, QTableWidgetItem(self.t1.item(rowCount - 2, j).text()))

想法是克隆 QTableWidgetItem 并将其插入第二个 table:

import sys
from PyQt5 import QtWidgets


def populate_table(table, prefix, rows, columns):
    table.clear()
    table.setColumnCount(columns)
    table.setRowCount(rows)
    for i in range(rows):
        for j in range(columns):
            it = QtWidgets.QTableWidgetItem("{} {}{}".format(prefix, i, j))
            table.setItem(i, j, it)


class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.resize(640, 480)

        self.spinbox1 = QtWidgets.QSpinBox()
        self.spinbox2 = QtWidgets.QSpinBox()
        self.button = QtWidgets.QPushButton("Move")
        self.table1 = QtWidgets.QTableWidget()
        self.table2 = QtWidgets.QTableWidget()

        lay = QtWidgets.QGridLayout(self)
        lay.addWidget(self.spinbox1, 0, 0)
        lay.addWidget(self.spinbox2, 0, 1)
        lay.addWidget(self.button, 1, 0, 1, 2)
        lay.addWidget(self.table1, 2, 0)
        lay.addWidget(self.table2, 2, 1)

        populate_table(self.table1, "Table1", 3, 4)
        populate_table(self.table2, "Table2", 4, 3)

        self.spinbox1.setMaximum(self.table1.rowCount() - 1)
        self.spinbox2.setMaximum(self.table2.rowCount() - 1)

        self.button.clicked.connect(self.handle_clicked)

    def handle_clicked(self):
        self.copy_rows(
            self.table1, self.spinbox1.value(), self.table2, self.spinbox2.value()
        )
        self.spinbox1.setMaximum(self.table1.rowCount() - 1)
        self.spinbox2.setMaximum(self.table2.rowCount() - 1)

    def copy_rows(self, from_table, row1, to_table, row2):
        if row1 >= from_table.rowCount():
            return

        if from_table.columnCount() > to_table.columnCount():
            to_table.setColumnCount(from_table.columnCount())

        if row2 >= to_table.rowCount() or row2 < 0:
            row2 = to_table.rowCount()

        to_table.insertRow(row2)

        for i in range(from_table.columnCount()):
            item = from_table.item(row1, i)
            if item is not None:
                to_table.setItem(row2, i, item.clone())


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())