Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 824
Max Lich Avatar asked Jul 24 '18 12:07

Max Lich


People also ask

How to set text align left in table header in qtcore?

In code above, we set the text in table header, then we set the text align left by setDefaultAlignment () function. table.horizontalHeader ().setDefaultAlignment (QtCore.Qt.AlignCenter) table.horizontalHeader ().setDefaultAlignment (QtCore.Qt.AlignRight)

Where can I find the qtableview?

The QTableView is the white box near the top. The first row of text (the "MAC Address Serial Number Device Name" is the header data (set in the model). The line that begins "b4:e6" is the first row of data in the table.

How do I style the alignment of the tabs within qtabbar?

The alignment of the tabs within the QTabBar is styled using the alignment property. To change the position of the QTabBar within a QTabWidget, use the tab-bar subcontrol (and set subcontrol-position).

How to style the background of the selected item in qtableview?

The color and background of the selected item is styled using selection-color and selection-background-color respectively. The corner widget in a QTableView is implemented as a QAbstractButton and can be styled using the " QTableView QTableCornerButton::section" selector.


2 Answers

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.

like image 88
cbuchart Avatar answered Sep 27 '22 20:09

cbuchart


I have found one of the solutions:

QHeaderView {
    qproperty-defaultAlignment: AlignHCenter AlignVCenter;
}

Although it works in WinCC OA only partially.

like image 20
Max Lich Avatar answered Sep 27 '22 20:09

Max Lich