1

我一直在尝试在 Qt tableWidget 中设置背景颜色。我非常希望得到您的帮助。这是我的代码。

QColor colorLive( Qt::red );
ui->tableWidget->setRowCount(14);
ui->tableWidget->setColumnCount(14);
for (int g = 0; g < 15; ++g)
{
    for (int i = 0; i < 15; ++i)
    {
        ui->tableWidget->setItem( g, i, new QTableWidgetItem );
        ui->tableWidget->item( g, i )->setBackgroundColor( colorLive );
        // error here
    }
}

应用程序输出接下来显示:The program has unexpectedly finished. 但是如果我将错误代码行更改为 ui->tableWidget->item( 0, 0 )->setBackgroundColor( colorLive ); ,那么它适用于一个单元格。但是,实际上,我需要设置所有单元格或其中的一部分。如果您能帮助我,我将不胜感激!

4

1 回答 1

0

您正在超出列数和行数。您将columnCountand设置rowCount为 14。这意味着有效范围是 0-13。但是在您的 for 循环中,您将遍历 0-14 行和 0-14 列。第 14 行和第 14 列无效。

这应该解决它:

int rows = 14;
int columns = 14;
QColor colorLive(Qt::red);
ui->tableWidget->setRowCount(rows);
ui->tableWidget->setColumnCount(columns);
for (int g = 0; g < rows; ++g)
{
    for (int i = 0; i < columns; ++i)
    {
        ui->tableWidget->setItem(g, i, new QTableWidgetItem);
        ui->tableWidget->item(g, i)->setBackgroundColor(colorLive);
    }
}
于 2013-11-04T07:16:42.627 回答