How to set cell border and background color in QTableWidgetItem?

N Alex picture N Alex · Mar 9, 2016 · Viewed 13.2k times · Source

I have a QTableWidget with 3 columns. 2 of the columns have some text in them, but one of them is empty and I want it to have a background color. Also I want the cells to have borders.

If I do

int i = 0;
foreach (tableData el, data) {
    //setting the first cell

    ui->eventTable->setItem(i, 1, new QTableWidgetItem); 
    //ui->eventTable->item(i, 1)->setBackground(el.severityColor);
    //ui->eventTable->item(i, 1)->setBackgroundColor(el.severityColor);
    ui->eventTable->item(i, 1)->setData(
        Qt::BackgroundRole,
        QBrush(el.severityColor)
    );

    //setting the third cell

    ++i;

}

everything works as expected.

But if before this code I try to add a border with

QString style(
    "QTableWidget::item {"
        "border: 1px solid white;"
    "}"
);
ui->eventTable->setStyleSheet(style);

the background is not set.

I tried with setBackground(), setBackgroundColor() (even though it is deprecated) and setData() as seen in the code, but the result is the same.

Also I tried setShowGrid(true) insted of the above stylesheet, but the border didn't show.

You can reproduce this by creating a table with 1 row and 1 column and trying to set the background of the cell, and then adding the stylesheet for a border.

Am I missing something? What else should I try? As an alternative, can I target specific rows/cells in the styles, so I can build a stylesheet string that does what I want?

Edit: I can have another styles in QTableWidget::item and they are applied, the problem is when I have a border. I also tried to write the border style as:

border-width: 1px;
border-style: solid;
border-color: white;

but still no luck. Also if I set the background from styles, it works. It doesn't work if I set it in code.

Answer

MildWolfie picture MildWolfie · Mar 11, 2016

Here are the properties you need to get your table styled appropriately. Note that gridline-color is the property that defines the borders of the items, which is defined in QTableView and not QTableView::item.

QTableView
{
    color: {color};
    border: 1px solid {color};
    background: {color};
    gridline-color: {color};
}
QTableView::item
{
    background: {color};
}

Obviously you would replace {color} with the appropriate colors for each property.