PyQt5替换QTableView的列顺序

PyQt5 replace column order QTableView

是否可以替换 QTableView 中列的顺序? 就像首先是“名字”,“年龄”,“地址”, 但我希望它更改为“年龄”、“姓名”、“地址”?

这在 PyQt5 中可行吗?

i = 0
            
            with open(f"{self.sender().file}", "r") as fileInput:
                
                for row in csv.reader(fileInput):
                    i+=1
                    if i == 1:
                        items = [
                            str(field)
                            for field in row
                        ]
                        CSVmodel.setHorizontalHeaderLabels(items)
                    else:
                        items = [
                            QtGui.QStandardItem(field)
                            for field in row
                        ]
                        CSVmodel.appendRow(items)

立即编码。

您只需更改索引:

ORDER = [1, 0, 2]

filename = f"{self.sender().file}"

with open(filename, "r") as f:
    for i, row in enumerate(csv.reader(f)):
        if i == 0:
            items = [str(field) for field in row]
            ordered_items = [items[i] for i in ORDER]
            CSVmodel.setHorizontalHeaderLabels(ordered_items)
        else:
            items = [QtGui.QStandardItem(field) for field in row]
            ordered_items = [items[i] for i in ORDER]
            CSVmodel.appendRow(ordered_items)