pyqt 动态更换表头和数据

发布于:2024-04-29 ⋅ 阅读:(22) ⋅ 点赞:(0)

目录

pyqt 动态更换表头和数据代码


效果图:

pyqt 动态更换表头和数据代码

from PyQt5.QtGui import QColor, QBrush
from PyQt5.QtWidgets import QApplication, QTableWidget, QVBoxLayout, QWidget, QPushButton, QTableWidgetItem


class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        # 初始化表格
        self.tableWidget = QTableWidget(self)

        self.column_colors = [QColor('red'), QColor('green'), QColor('blue'),  QColor('purple'), QColor('orange'), QColor('pink'), QColor('lightblue'), QColor('lightgreen')]


        self.setWindowTitle('I问财')
        self.setGeometry(100, 100, 800, 600)
        header = self.tableWidget.horizontalHeader()
        header.setStyleSheet("QHeaderView::section { background-color: white ; color: red; font-weight: bold; }")
        # 创建一个按钮,用于改变表格数据和表头
        btn = QPushButton('Change to New Data', self)
        btn.clicked.connect(self.loadNewData)
        self.updateTable(['Name', 'Age', 'Country'], [['Alice', '24', 'USA'], ['Bob', '30', 'Canada'], ['Charlie', '28', 'UK']])
        # 布局
        layout = QVBoxLayout()
        layout.addWidget(self.tableWidget)
        layout.addWidget(btn)
        self.setLayout(layout)

    def updateTable(self, headers, data):
        # 设置列数
        column_count = len(headers)
        self.tableWidget.setColumnCount(column_count)
        self.tableWidget.setRowCount(len(data))
        self.setGeometry(100, 100, 600, 600)
        # 设置表头
        self.tableWidget.setHorizontalHeaderLabels(headers)
        self.tableWidget.setShowGrid(True)
        # 填充数据
        for row_index, row in enumerate(data):
            for column, item in enumerate(row):
                item = QTableWidgetItem(item)
                item.setForeground(QBrush(self.column_colors[column % len(self.column_colors)]))  # 根据列设置文本颜色
                self.tableWidget.setItem(row_index, column,item)

    def loadNewData(self):
        # 新数据集和表头
        new_headers = ['First Name', 'Last Name', 'Email', 'Country']
        new_data = [['Alice', 'Smith', 'alice.smith@example.com', 'USA'], ['Bob', 'Brown', 'bob.brown@example.com', 'Canada']]

        # 更新表格
        self.updateTable(new_headers, new_data)


if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    sys.exit(app.exec_())