本来想找找QT里有没有现成的API的,结果没有找到,只能自己写了。
实现也好实现,QTableWidgetItem里面有修改背景色的API,直接调用,然后用循环控制隔行换色即可。
实现代码:
void testtt::changeColor(QTableWidget *tablewidget){
for (int i = 0;i < tablewidget->rowCount();i++)
{
if (i % 2 == 0)
{
for (int j = 0;j < tablewidget->columnCount();j++)
{
QTableWidgetItem *item = tablewidget->item(i,j);
if (item)
{
const QColor color = QColor(252,222,156);
item->setBackgroundColor(color);
}
}
}
}
}
效果:
注意:
QTableWidget里面必须对应的item不为空的地方才可以设置背景色,所以每次要判断下,不然如果有的地方就没加item就对他设置背景程序就会崩。
实现也好实现,QTableWidgetItem里面有修改背景色的API,直接调用,然后用循环控制隔行换色即可。
实现代码:
void testtt::changeColor(QTableWidget *tablewidget){
for (int i = 0;i < tablewidget->rowCount();i++)
{
if (i % 2 == 0)
{
for (int j = 0;j < tablewidget->columnCount();j++)
{
QTableWidgetItem *item = tablewidget->item(i,j);
if (item)
{
const QColor color = QColor(252,222,156);
item->setBackgroundColor(color);
}
}
}
}
}
效果:
![](https://i-blog.csdnimg.cn/blog_migrate/7dc9119d27b419a10619deb02e558e3d.jpeg)
注意:
QTableWidget里面必须对应的item不为空的地方才可以设置背景色,所以每次要判断下,不然如果有的地方就没加item就对他设置背景程序就会崩。