简体   繁体   English

如何从 Qt 上的标题(水平/垂直)QTableWidget 更改背景颜色?

[英]How to change the background color from the header(horizontal / vertical) QTableWidget on Qt?

I would like to know how to change the background color from the headers (horizontal / vertical) from the object QTableWidget on Qt .我想知道如何从Qt上的对象QTableWidget更改标题(水平/垂直)的背景颜色。

I already Know how to change all the headers together, using :我已经知道如何一起更改所有标题,使用:

ui->tableWidget->setStyleSheet("QHeaderView::section {background-color:red}");

But I need change individually the items.但我需要单独更改这些项目。 Obviously if this is possible .显然,如果这是可能的。

There are at least 2 ways to solve this problem.至少有两种方法可以解决这个问题。 Very easy one:很简单的一个:

Just use setHeaderData() and set specific colors for specific sections.只需使用setHeaderData()并为特定部分设置特定颜色。

QTableView *tview = new QTableView;

QStandardItemModel *md = new QStandardItemModel(4, 4);
for (int row = 0; row < 4; ++row) {
    for (int column = 0; column < 4; ++column) {
        QStandardItem *item = new QStandardItem(QString("row %0, column %1").arg(row).arg(column));
        md->setItem(row, column, item);
    }
}
tview->setModel(md);
tview->model()->setHeaderData(0,Qt::Horizontal,QBrush(QColor("red")),Qt::BackgroundRole);
tview->show();

But u nfortunately it will not work on some systems... Qt uses the platform style.但不幸的是,它不适用于某些系统... Qt 使用平台样式。 For example, my Windows doesn't allow to change header's color.例如,我的 Windows 不允许更改标题的颜色。 So this code doesn't work on my machine.所以这段代码在我的机器上不起作用。 Fortunately, it can be solved easily with changing global style.幸运的是,可以通过更改全局样式轻松解决。 So next code works:所以下一个代码有效:

//... same code ...
tview->show();
QApplication::setStyle(QStyleFactory::create("Fusion"));

If you don't want to change style, then you should create your own HeaderView .如果您不想更改样式,则应创建自己的HeaderView Probably, something similar as here .可能与此处类似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM