2014-04-13 68 views
2

雖然自定義QTreeView小部件,其中每個項目是由不同的部件組成(combo box,line edit等),我遇到了一個問題,無法自定義標題標籤(列的名稱)。隨着QTreeWidget()setHeaderLabels([]) ...PyQt如何設置標題標籤與QTreeView

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_()) 
+1

像這樣的事情? self.itemModel.setHorizo​​ntalItem(0,QtGui.QStandardItem('Column1')) – alien

回答

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")) 

最後一行應該是你的循環之外。它設置你的0索引列標題。當你在你的循環中迭代1到7時,其他的將被設置。

輸出看起來是這樣的:

Headers are set


相關問題