自定义QTreeView
窗口小部件,其中每个项目由不同的窗口小部件(combo box
,line edit
等)组成一行,我遇到了一个无法自定义的问题标题标签(列的名称)。使用QTreeWidget()
时,setHeaderLabels([])
...
import sys, os
from PyQt4 import QtCore,QtGui
class TreeWidgetsItems(QtGui.QTreeView):
def __init__(self):
super(TreeWidgetsItems, self).__init__()
self.itemModel = QtGui.QStandardItemModel(0, 2)
self.setModel(self.itemModel)
item0 = QtGui.QStandardItem('Item 0')
self.itemModel.setItem(0, 0, item0)
item0.setCheckable(True)
item1 = QtGui.QStandardItem('Item 1')
self.itemModel.setItem(0, 1, item1)
item2 = QtGui.QStandardItem('Item 2')
self.itemModel.setItem(0, 2, item2)
item3 = QtGui.QStandardItem('Item 3')
self.itemModel.setItem(0, 3, item3)
lineedit1 = QtGui.QLineEdit()
itemIndex1 = self.itemModel.index(0, 1, QtCore.QModelIndex())
self.setIndexWidget(itemIndex1, lineedit1)
self.combo2 = QtGui.QComboBox()
itemIndex2 = self.itemModel.index(0, 2, QtCore.QModelIndex())
self.setIndexWidget(itemIndex2, self.combo2)
for i in range(5):
self.combo2.addItem('Item'+str(i))
self.dateEdit = QtGui.QDateEdit()
self.dateEdit.setDateTime(QtCore.QDateTime.currentDateTime())
self.dateEdit.setMaximumDate(QtCore.QDate(7999, 12, 28))
self.dateEdit.setMaximumTime(QtCore.QTime(23, 59, 59))
self.dateEdit.setCalendarPopup(True)
itemIndex3 = self.itemModel.index(0, 3, QtCore.QModelIndex())
self.setIndexWidget(itemIndex3, self.dateEdit)
self.setColumnWidth(0, 60)
for i in range(1, 7):
self.setColumnWidth(i, 200)
self.show()
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = TreeWidgetsItems()
window.resize(960, 240)
sys.exit(app.exec_())
答案 0 :(得分:3)
将for i in range(1, 7):
循环更改为:
for i in range(1, 7):
self.setColumnWidth(i, 200)
self.itemModel.setHeaderData(i, QtCore.Qt.Horizontal, 'Column {}'.format(i))
self.itemModel.setHeaderData(0, QtCore.Qt.Horizontal, 'Column {}'.format("0"))
最后一行应该在你的for循环之外。它正在设置您的0索引列标题。其他将在您循环中从1到7迭代时设置。
输出如下: