2011-08-25 186 views

回答

4

據我所知,有沒有簡單的方法來做到這一點。您必須總結表格列的寬度,然後爲標題添加空間。您還必須爲垂直滾動條和小部件框架添加空間。這裏是一個辦法做到這一點,

class myTableWidget(QtGui.QTableWidget): 

    def sizeHint(self): 
     width = 0 
     for i in range(self.columnCount()): 
      width += self.columnWidth(i) 

     width += self.verticalHeader().sizeHint().width() 

     width += self.verticalScrollBar().sizeHint().width() 
     width += self.frameWidth()*2 

     return QtCore.QSize(width,self.height()) 
6

你可以使用類似的東西(註釋足夠我希望):

from PyQt4.QtCore import * 
from PyQt4.QtGui import * 

class MyTableWidget(QTableWidget): 
    def __init__(self, x, y, parent = None): 
     super(MyTableWidget, self).__init__(x, y, parent) 

     self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) 
     self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn) 

     # To force the width to use sizeHint().width() 
     self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) 

     # To readjust the size automatically... 
     # ... when columns are added or resized 
     self.horizontalHeader().geometriesChanged \ 
      .connect(self.updateGeometryAsync) 
     self.horizontalHeader().sectionResized \ 
      .connect(self.updateGeometryAsync)   
     # ... when a row header label changes and makes the 
     # width of the vertical header change too 
     self.model().headerDataChanged.connect(self.updateGeometryAsync) 

    def updateGeometryAsync(self):  
     QTimer.singleShot(0, self.updateGeometry) 

    def sizeHint(self): 
     height = QTableWidget.sizeHint(self).height() 

     # length() includes the width of all its sections 
     width = self.horizontalHeader().length() 

     # you add the actual size of the vertical header and scrollbar 
     # (not the sizeHint which would only be the preferred size)     
     width += self.verticalHeader().width()   
     width += self.verticalScrollBar().width()  

     # and the margins which include the frameWidth and the extra 
     # margins that would be set via a stylesheet or something else 
     margins = self.contentsMargins() 
     width += margins.left() + margins.right() 

     return QSize(width, height) 

當行標題的變化,整個垂直頭部的變化寬度,但在發出信號headerDataChanged後不立刻。
這就是爲什麼我使用QTimer來調用updateGeometry(必須在sizeHint更改時調用)(QTableWidget實際更新了垂直標頭寬度後)。

+0

這對我很好,而'接受'的答案沒有。其中一個原因可能是我使用的QTableView沒有在Terry先生的解決方案中使用的columnCount方法。請注意,對於QTableView,您需要在構造函數的早期階段爲該解決方案設置模型,因爲它使用模型來判斷標題是否更改。 –

+0

警告之詞:我在一個未保存的對話框中使用了MyTableWidget的實現(例如,對話框被創建並在同一個方法中超出了範圍),它給了我一個'RuntimeError:包裝的C/C++對象MyTableWidget類型已被刪除「錯誤。我認爲''QTimer'試圖在widget已經被垃圾收集後調用'self.updateGeometry'(這可能嗎?)。在任何情況下,我只是通過調用股票'self.updateGeometry'來將調用替換爲'self.updateGeometryAsync',它對我來說仍然很好。 – jeremiahbuddha