How to align text in a header of QTableView in Qt using only CSS?
Asked Answered
D

2

5

I tried the CSS code:

QTableView QHeaderView::section {
    text-align: center;
 }

And it did not help me.

PS I write the SCADA system in the WinCC OA that uses Qt, and there you can change the appearance of components only using CSS

Dosia answered 24/7, 2018 at 12:40 Comment(4)
table header is used as thead, so you can write thead tr th {text-align: center;}Lactometer
@Sonia, it is not HTML, it is Qt and its graphic objects. So there are other CSS selectors here.Dosia
@MaxLich, QSS to be precise. Here you can see what is available for each class.Sphinx
@Sphinx Thank you, but I have already seen itDosia
S
4

As seen in the source code for QHeaderView::paintSection

QVariant textAlignment = d->model->headerData(logicalIndex, d->orientation,
                                              Qt::TextAlignmentRole);
opt.rect = rect;
opt.section = logicalIndex;
opt.state |= state;
opt.textAlignment = Qt::Alignment(textAlignment.isValid()
                                  ? Qt::Alignment(textAlignment.toInt())
                                  : d->defaultAlignment);

QHeaderView does not uses the stylesheet to define the text alignment, only values from the defaultAlignment or the data from the header's model (Qt::TextAlignmentRole).

Now, if your default alignment is either Qt::AlignLeft or Qt::AlignRight, you can use the section padding to automatically center it:

QTableView QHeaderView::section {
    padding-left: auto;
    padding-right: auto;
}

The opposite is not true: if default alignment is center, other calculus affect how padding is used and cannot be used to automatically left- or right-align text.

Switcheroo answered 25/7, 2018 at 8:39 Comment(0)
D
3

I have found one of the solutions:

QHeaderView {
    qproperty-defaultAlignment: AlignHCenter AlignVCenter;
}

Although it works in WinCC OA only partially.

Dosia answered 25/7, 2018 at 10:34 Comment(1)
Interesting access to properties from within the stylesheet, didn't know about it!Switcheroo

© 2022 - 2024 — McMap. All rights reserved.