[英]how to set the QTableView header name in Pyqt4
我想知道如何在QTableview中設置自定義標題名稱
當我創建一個QTableview時,我得到列和行標題名稱為1,2,3,4。 我想知道如何設置自己的列和標題標題。
我根據需要得到了解決方案 ,希望它可以幫助遇到相同情況的人
如果您在自己的模型中使用QTableView
,則需要在模型中實現headerData()
方法以返回標頭的數據。 這是一個僅顯示列標題的片段 - 更改header_labels
值以更改標題文本。
class TableModel(QAbstractTableModel):
header_labels = ['Column 1', 'Column 2', 'Column 3', 'Column 4']
def __init__(self, parent=None):
QAbstractTableModel.__init__(self, parent)
def headerData(self, section, orientation, role=Qt.DisplayRole):
if role == Qt.DisplayRole and orientation == Qt.Horizontal:
return self.header_labels[section]
return QAbstractTableModel.headerData(self, section, orientation, role)
原始海報產生了以下代碼作為解決方案(或者在主持人刪除的pastebin鏈接中發布):
from PyQt4 import QtCore, QtGui
class myWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(myWindow, self).__init__(parent)
self.centralwidget = QtGui.QWidget(self)
self.view = QtGui.QTableView(self.centralwidget)
self.view.setSortingEnabled(True)
self.gridLayout = QtGui.QGridLayout(self.centralwidget)
self.gridLayout.addWidget(self.view, 1, 0, 1, 3)
self.setCentralWidget(self.centralwidget)
self.model = QtGui.QStandardItemModel(self)
for rowName in range(3) * 5:
self.model.invisibleRootItem().appendRow(
[ QtGui.QStandardItem("row {0} col {1}".format(rowName, column))
for column in range(3)
]
)
for column in range(3):
self.model.setHeaderData(column, QtCore.Qt.Horizontal,
'Column %d' % int(column+1))
for row in range(3 * 5):
self.model.setHeaderData(row, QtCore.Qt.Vertical,
'Row %d' % int(row+1))
self.proxy = QtGui.QSortFilterProxyModel(self)
self.proxy.setSourceModel(self.model)
self.view.setModel(self.proxy)
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
main = myWindow()
main.show()
main.resize(400, 600)
sys.exit(app.exec_())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.