如何仅使用CSS在Qt中的QTableView标题中对齐文本?

时间:2018-07-24 12:40:40

标签: qt qtableview qtstylesheets qheaderview

我尝试了CSS代码:

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

它并没有帮助我。

PS我在使用Qt的WinCC OA中编写了SCADA系统,在那里您只能使用CSS更改组件的外观

2 个答案:

答案 0 :(得分:2)

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不使用样式表定义文本对齐方式,仅使用defaultAlignment中的值或标头模型(Qt::TextAlignmentRole)中的数据。

现在,如果您的默认对齐方式是Qt::AlignLeftQt::AlignRight,则可以使用部分填充将其自动居中:

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

事实并非如此:如果默认对齐方式为居中,则其他演算会影响填充的使用方式,并且不能用于自动左对齐或右对齐文本。

答案 1 :(得分:2)

我找到了一种解决方案:

QHeaderView {
    qproperty-defaultAlignment: AlignHCenter AlignVCenter;
}

尽管它在WinCC OA中仅部分起作用。

相关问题