qtdatatablebackground-colorqtextdocumentqtextcursor

Alternating row background in QTextTable


I am trying to create a printable document using QTextDocument, which also includes a table, which I am adding using QTextCursor::insertTable. However I have the requirement to use different background colors for the table rows. The table is meant to contain all days of a month, and weekends should have grey background, while workdays shall have no background.

I have tried this code:

    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);
        }
    }

Now the issue with this is that the table->setFormat changes the format of the whole table, and I can't seem to find any function which lets me set the format for a row or a cell. There is formatting options for cells, however those are for the text format, and thus would not color the cell background.

I have also tried using QTextDocument::insertHTML and work with HTML tables, however Qt would not render the CSS correctly which I would use for styling the borders and so on.

How can I achieve alternating row background colors in QTextTable?


Solution

  • You can use QTextTableCell:setFormat to change the background color of each cell:

    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);
        }
    }