2016-07-25 33 views

回答

1

使用QStyledItemDelegate是正確的方法。在你sizehinz功能,您可以使用樣式選項textQFontMetrics類:

QSize MyItemDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override { 
    QSize baseSize = this->QStyledItemDelegate::sizeHint(option, index); 
    baseSize.setHeight(10000);//something very high, or the maximum height of your text block 

    QFontMetrics metrics(option.font); 
    QRect outRect = metrics.boundingRect(QRect(QPoint(0, 0), baseSize), Qt::AlignLeft, option.text); 
    baseSize.setHeight(outRect.height()); 
    return baseSize; 
} 

注:現在我不能對此進行測試,但它應該工作。您可能需要調整調用metrics.boundingRect如果輸出不適合您的需求

編輯:
看來sizeHint將只調用一次以創建初始佈局,但不調整列後。

最後的想法可能是覆蓋QAbstractItemModel::data函數以使用Qt::SizeHintRole返回所需的大小。你既可以把它添加到您現有的模型或提供代理模型要做到這一點:

QSize MyModel::data(const QModelIndex &index, int role) const override { 
    switch(role) { 
     //... 
    case Qt::SizeHintRole: 
    { 
     QSize baseSize(getFixedWidth(index.column()), baseSize.setHeight(10000));//something very high, or the maximum height of your text block 

     QFontMetrics metrics(this->data(index, Qt::FontRole).value<QFont>()); 
     QRect outRect = metrics.boundingRect(QRect(QPoint(0, 0), baseSize), Qt::AlignLeft, this->data(index, Qt::DisplayRole))); 
     baseSize.setHeight(outRect.height()); 
     return baseSize; 
    } 
     //... 
    } 
} 

重要提示:每當你視圖獲取大小,你將不得不發出dataChanged信號對所有這些項目。 getFixedWidth是你必須實現的東西,以返回給定列的當前寬度。

+0

好的,它的工作原理!但是如何讓細胞再次調整大小? – Rinat

+0

我不確定你的意思?調整標題部分的大小? – Felix

+0

是的,行在加載時調整大小,但在更改標題部分和列寬度時更改大小 – Rinat

相關問題