实现效果:
代码
from chatgpt
import sys
from PyQt5.QtWidgets import QApplication, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget
from PyQt5.QtCore import Qtclass TableDemo(QWidget):def __init__(self):super().__init__()# 创建表格self.table_widget = QTableWidget()# 设置行和列数self.table_widget.setRowCount(3)self.table_widget.setColumnCount(3)# 设置表格头部self.table_widget.setHorizontalHeaderLabels(["Name", "Age", "Country"])# 插入数据self.table_widget.setItem(0, 0, QTableWidgetItem("Alice"))self.table_widget.setItem(0, 1, QTableWidgetItem("30"))self.table_widget.setItem(0, 2, QTableWidgetItem("USA"))self.table_widget.setItem(1, 0, QTableWidgetItem("Bob"))self.table_widget.setItem(1, 1, QTableWidgetItem("25"))self.table_widget.setItem(1, 2, QTableWidgetItem("Canada"))self.table_widget.setItem(2, 0, QTableWidgetItem("Charlie"))self.table_widget.setItem(2, 1, QTableWidgetItem("35"))self.table_widget.setItem(2, 2, QTableWidgetItem("UK"))# 启用排序功能self.table_widget.setSortingEnabled(True)# 自定义表头排序箭头样式self.table_widget.setStyleSheet("""QHeaderView::section {background-color: lightgray;padding: 4px;border: 1px solid gray;}QHeaderView::up-arrow {width: 6px;height: 6px;image: url(升序.png); /* 使用自定义的图片替换 */padding-right: 10px; /* 调整箭头右侧的间距 */}QHeaderView::down-arrow {width: 6px;height: 6px;image: url(排序.png); /* 使用自定义的图片替换 */padding-right: 10px; /* 调整箭头右侧的间距 */}""")# 布局layout = QVBoxLayout()layout.addWidget(self.table_widget)self.setLayout(layout)# 设置窗口标题self.setWindowTitle("Table with Custom Sorting Arrow Style")if __name__ == "__main__":app = QApplication(sys.argv)demo = TableDemo()demo.show()sys.exit(app.exec_())