问题
I need to determine the VISIBLE width of a column within a QTreeWidget.
I'll explain my problem with a small example.
A QTreeWidget defines three columns with the fixed width of col 1=200 px, col 2=100 px and col 3=300 px. The widget itself has a ( resizeable ) width of 350.
The width of all colums ( 200 + 100 + 300 = 600 ) exeeds the with of the widget, so a scrollbar is shown.
For some special calculation I need to know the visible width of the third column:
Case A would be quite easy, I just need to subtract: widget - col 1 - col2 = 350 - 200 - 100 = 50.
But what should I do in case B? To calculate the visible width of col 3 I need to know the visible width of col 1.
Is there a designated way to determine the visible width of a column?
Thanks, Sören
Addon:
I was asked for the purpose of my question. In our software, we have a kind of oscilloscope function. While most of the recorded values are numbers (with units), some of our data sources contain other types of information.
The layout of the page is basically structured in such a way that there is a graphics view and a QTreeWidget with the display of the values, which can be changed in their relation to each other using splitters.
The QTreeWidget contains several columns, the last column representing the actual recorded value.
The column width is automatically adjusted to the content, so that the user does not have to constantly correct the column width.
Now the display in the value column should be right-aligned. But if there is a very long text there, the remaining measured values on the right disappear in nirvana and you have to make the QTreeWidget very wide to see the values again:
The idea now is to display the values right-aligned only if they fit completely into the currently visible area of the column and to start left-aligned otherwise. The alignment is not right-aligned with the column, but right-aligned with the visible area:
Therefore I first adjust all elements left-aligned. I overwrite the method
void drawRow( QPainter * apPainter
, const QStyleOptionViewItem & arceOption
, const QModelIndex & arcIndex
) const override;
and check there whether the display text fits into the visible area (using QFontMetrics of the apPainter).
If this is the case and the width of the display text is even smaller than the visible width, I add enough free space so that the text is always right-aligned in the visible area of the column.
Currently, I help myself with the scrollbar by calculating the document width, slider position, width of the QTreeView and its individual column widths, which works reasonably well. But I am still looking for an elegant solution.
回答1:
You can try QAbstractItemView::visualRect() - it gives you the coordinates relative to the viewport.
来源:https://stackoverflow.com/questions/60743915/determine-visible-size-of-a-qtreewidget-column