Skip to content
Advertisement

How to word wrap the header contents of QTableWidget in PyQt5 Python

I am working on PyQt5 where I have a QTableWidget. It has a header column which I want to word wrap. Below is how the table looks like:

enter image description here

As we can see that the header label like Maximum Variation Coefficient has 3 words, thus its taking too much column width. How can wrap the words in the header.

Below is the code:

JavaScript

I tried adding this self.tableWidget.setWordWrap(True) but this doesnt make any change. Can anyone give some good solution. Please help. Thanks

EDIT:

Also tried this :

JavaScript

But it didnt worked

Advertisement

Answer

In order to achieve what you need, you must set your own header and proceed with the following two assumptions:

  • the header must provide the correct size hint height according to the section contents in case the width of the column is not sufficient;
  • the text alignment must include the QtCore.Qt.TextWordWrap flag, so that the painter knows that it can wrap text;

Do note that, while the second aspect might be enough in some situations (as headers are normally tall enough to fit at least two lines), the first point is mandatory as the text might require more vertical space, otherwise some text would be cut out.


The first point requires to subclass QHeaderView and reimplement sectionSizeFromContents():

JavaScript

Then, to set the word wrap flag, there are two options:

  1. set the alignment flag on the underlying model with setHeaderData() for each existing column:
JavaScript
  1. Use a QProxyStyle to override the painting of the header, by applying the flag on the option:
JavaScript

Finally, consider that:

  • using setSectionResizeMode with ResizeToContents or Stretch, along with setStretchLastSection, will always cause the table trying to use as much space as required by the headers upon showing the first time;

  • by default, QHeaderView sections are not clickable (which is a mandatory requirement for sorting) and the highlightSections property is also False; both QTableView and QTableWidget create their headers with those values as True, so when a new header is set you must explicitly change those aspects if sorting and highlighting are required:

    JavaScript
  • both sorting and section highlighting can create some issues, as the sort indicator requires further horizontal space and highlighted sections are normally shown with a bold font (but are shown normally while the mouse is pressed); all this might create some flickering and odd behavior; unfortunately, there’s no obvious solution for these problems, but when using the QProxyStyle it’s possible to avoid some flickering by overriding the font style:

    JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement