QTextTable 中的交替行背景

Alternating row background in QTextTable

我正在尝试使用 QTextDocument 创建一个 printable 文档,其中还包括一个 table,我正在使用 QTextCursor::insertTable 添加它。 但是我需要为 table 行使用不同的背景颜色。 table是为了包含一个月中的所有日子,周末应该有灰色背景,而工作日应该没有背景。

我试过这个代码:

    QTextTable* table = cursor.insertTable(1, 7, normal);   // 7 columns, and first row containing header

    foreach (DayItem* day, month->days)
    {
        if (day->date.dayOfWeek() == 6 || day->date.dayOfWeek() == 7)
        {
            table->setFormat(background);       // grey background
            table->appendRows(1);
        }
        else
        {
            table->setFormat(normal);           // white background
            table->appendRows(1);
        }
    }

现在的问题是 table->setFormat 改变了 whole table 的格式,我似乎找不到任何功能这让我可以设置 rowcell 的格式。有单元格的格式选项,但这些选项适用于 文本格式 ,因此不会为单元格背景着色。

我也尝试过使用 QTextDocument::insertHTML 并使用 HTML tables,但是 Qt 无法正确渲染 CSS,而我将使用它来设置边框样式等等。

如何在 QTextTable 中实现交替行背景颜色?

您可以使用QTextTableCell:setFormat更改每个单元格的背景颜色:

auto edit = new QTextEdit();

auto table = edit->textCursor().insertTable(3, 2);
for(int i = 0; i < table->rows(); ++i)
{
    for(int j = 0; j < table->columns(); ++j)
    {
        auto cell = table->cellAt(i, j);
        auto cursor = cell.firstCursorPosition();
        cursor.insertText(QString("cell %1, %2").arg(i).arg(j));

        auto format = cell.format();
        format.setBackground(i%2 == 0 ? Qt::red : Qt::green);
        cell.setFormat(format);
    }
}