QTableView header word wrap

Viewed 3902

I'm trying to set the horizontal and vertical headers in QTableView to word wrap but without any success.

I want to set all columns to be the same width (including the vertical header), and those columns that have multiline text to word wrap. If word is wider than the column it should elide right. I've managed to set the elide using QTableView -> horizontalHeader() -> setTextElideMode(Qt::ElideRight), but I can't do the same for word wrap since QHeaderView doesn't have setWordWrap method. So event if text is multiline it will just elide. Setting the word wrap on the table view doesn't do anything. The table cells contain only small numbers so the issue is only with the headers, and I want to avoid using '/n' since the headers are set dynamically. Is there maybe some other setting I've changed that's not allowing word wrap to function?

4 Answers

I was able to consolidate the two approaches above (c++, Qt 5.12) with a pretty nice result. (no hideheaders on the model)

  1. Override QHeaderView::sectionSizeFromContents() such that size accounts for text wrapping
QSize MyHeaderView::sectionSizeFromContents(int logicalIndex) const 
{
    const QString text = this->model()->headerData(logicalIndex, this->orientation(), Qt::DisplayRole).toString();
    const int maxWidth = this->sectionSize(logicalIndex);
    const int maxHeight = 5000; // arbitrarily large
    const auto alignment = defaultAlignment();
    const QFontMetrics metrics(this->fontMetrics());
    const QRect rect = metrics.boundingRect(QRect(0, 0, maxWidth, maxHeight), alignment, text);

    const QSize textMarginBuffer(2, 2); // buffer space around text preventing clipping
    return rect.size() + textMarginBuffer;
}
  1. Set the default alignment to have word wrap (optionally, center)
 tableview->horizontalHeader()->setDefaultAlignment(Qt::AlignCenter | (Qt::Alignment)Qt::TextWordWrap);

An open Qt issue from 2010 on this suggests that this may not be easily possible. However, according to the only comment from 2015, there is a simple workaround for this very issue which goes like this:

   myTable->horizontalHeader()->setDefaultAlignment(Qt::AlignCenter | (Qt::Alignment)Qt::TextWordWrap);

I just tested with Qt 5.12 and fortunately found it still working.

In python:

myTableView.horizontalHeader().setDefaultAlignment(Qt.AlignCenter | Qt.Alignment(Qt.TextWordWrap))

Related