如何根据标题长度设置QTableView列宽
{"title":"如何根据标题长度设置QTableView列宽","description":"本文介绍如何使用PyQt5的QTableView组件,根据header标题的长度来设置列宽。示例代码演示了使用setColumnWidth()函数和sectionSizeHint()函数实现这一功能。","keywords":"QTableView, PyQt5, 列宽, header, sectionSizeHint, setColumnWidth","content":"要根据header的长度来设置QTableView的列宽,可以使用setColumnWidth()函数。以下是一个示例代码:\n\npython\nfrom PyQt5.QtWidgets import QApplication, QTableView, QHeaderView, QVBoxLayout, QWidget\n\napp = QApplication([])\nwindow = QWidget()\nlayout = QVBoxLayout(window)\ntable = QTableView()\nlayout.addWidget(table)\n\n# 设置header的内容\nheader = QHeaderView()\nheader.setSectionResizeMode(QHeaderView.ResizeToContents)\nheader.setStretchLastSection(True)\ntable.setHorizontalHeader(header)\ntable.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n\n# 设置列宽\nmodel = QStandardItemModel(0, 3)\nmodel.setHorizontalHeaderLabels(["Header1", "Header2", "Header3"])\ntable.setModel(model)\n\nfor i in range(3):\n model.setHeaderData(i, Qt.Horizontal, "Header" + str(i+1))\n width = table.horizontalHeader().sectionSizeHint(i)\n table.setColumnWidth(i, width)\n\nwindow.show()\napp.exec_()\n\n\n在这个示例中,我们创建了一个QStandardItemModel,并设置了3个列的header。然后,我们使用sectionSizeHint()函数来获取header的长度,然后使用setColumnWidth()函数来设置列宽。"}
原文地址: https://www.cveoy.top/t/topic/qDb0 著作权归作者所有。请勿转载和采集!