排序后的QTableWidget不完整填充

问题描述 投票:0回答:1

我有一个QTableWidget,它将填充一些随机值。该表已启用排序:tableWidget.setSortingEnabled(True)。排序工作正常(我知道,在这个最小的示例中,它将是字母数字排序)。

但是,当我按一列对表格进行排序,然后在SO上用tableWidget.clear()tableWidget.clearContent()tableWidget.setRowCount(0)的各种建议清除表格并重新填充表格时,该表格将被不完整地填充。我已经注意到,在对列进行排序之前,表将不完全填充。因此,对最后一列进行排序将导致完全重新填充表格。但这不是可接受的解决方法。

但是我在这里想念什么?如何始终完全重新填充表格?

代码:

import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QAction, QTableWidget, QTableWidgetItem, QVBoxLayout, QPushButton
from PyQt5.QtCore import pyqtSlot
import random

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 table'
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(0,0,700,500)
        self.layout = QVBoxLayout()

        self.tableWidget = QTableWidget()
        self.tableWidget.setSortingEnabled(True)
        self.layout.addWidget(self.tableWidget)

        self.pb_refill = QPushButton("Refill")
        self.pb_refill.clicked.connect(self.on_click_pb_refill)
        self.layout.addWidget(self.pb_refill)

        self.setLayout(self.layout) 
        self.show()

    @pyqtSlot()
    def on_click_pb_refill(self):
        # self.tableWidget.clear()
        # self.tableWidget.clearContents()
        self.tableWidget.setRowCount(0)
        rows_random = int(random.random()*7)+5
        self.tableWidget.setRowCount(rows_random)
        self.tableWidget.setColumnCount(6)
        for row in range(rows_random):
            for col in range(6):
                number = random.random()
                self.tableWidget.setItem(row, col, QTableWidgetItem(str(number)))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

结果:(排序并重新填充后)

enter image description here

python sorting pyqt qtablewidget
1个回答
0
投票

问题是,当您添加项目时,您要进行重新排序,例如,假设您正确插入了第一行的值,但是随后您在(1,0)中输入了一个小于项目(0 ,0)将被重新排序(项目(0,j)将是(1,j)),并且在插入时设置项目(1,1)将替换占据位置(0,1)的项目(0,2)将保持为空。

解决方案是通过填充表来禁用排序。

@pyqtSlot()
def on_click_pb_refill(self):
    self.tableWidget.clear()
    self.tableWidget.setSortingEnabled(False)
    rows_random = int(random.random() * 7) + 5
    self.tableWidget.setRowCount(rows_random)
    self.tableWidget.setColumnCount(6)
    for row in range(rows_random):
        for col in range(6):
            number = random.random()
            self.tableWidget.setItem(row, col, QTableWidgetItem(str(number)))
    self.tableWidget.setSortingEnabled(True)
© www.soinside.com 2019 - 2024. All rights reserved.