1

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

我试过这段代码:

    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改变了整个表格的格式,我似乎找不到任何可以让我设置rowcell格式的函数。单元格有格式化选项,但这些选项是针对文本格式的,因此不会为单元格背景着色。

我也尝试过使用QTextDocument::insertHTML和处理 HTML 表格,但是 Qt 无法正确呈现我将用于设置边框样式等的 CSS。

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

4

1 回答 1

4

您可以使用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);
    }
}
于 2019-12-11T09:37:44.793 回答