PDA

View Full Version : How to set background color one row in TableWidget?



TomASS
28th September 2009, 21:27
Hi,

I've a TableWidget:


TableResult = new QTableWidget;
TableResult->setRowCount(10);
TableResult->setColumnCount(5);
for(int c=1;c<5;c++){
for(int r=1;r<10;r++){
QTableWidgetItem *tmpItem;
tmpItem= new QTableWidgetItem(tr("%1 x %2").arg(c).arg(r));
TableResult->setItem(r, c, tmpItem);
}
}

How to set background color rows number 1, 3, 5, 7, 9 to (example) blue, and rows number 2,4,6,8 to red?

If I had a model-view-delegate pattern, I could do it in delegate, but I've any view, any model, any delegate :/

ChiliPalmer
29th September 2009, 00:28
TableResult = new QTableWidget;
TableResult->setRowCount(10);
TableResult->setColumnCount(5);

QTableWidgetItem *tmpItem; //why create a new item on the heap in every loop pass?
QBrush blue(Qt::blue);
QBrush red(Qt::red);

for(int c=0;c<4;c++) {
for(int r=0;r<9;r++){
tmpItem= new QTableWidgetItem(tr("%1 x %2").arg(c + 1).arg(r + 1));

if (r % 2 == 1)
tmpItem->setForeground(blue)
else
tmpItem->setForeground(red);
TableResult->setItem(r, c, tmpItem);
}
}

There you have it, pretty simple.
But if you really just want to alternate the row colors, this (http://doc.trolltech.com/4.5/qabstractitemview.html#alternatingRowColors-prop) would be much better.


Edit:
I almost forgot: you're starting with 1 in both your for-loops. Remember that the TableWidgets indexes start at 0 and end at rowCount - 1. I have corrected that, s.a.

Edit 2:
Of course you can use a delegate with a QTableWidget, it's also part of the model-view architecture.
See here (http://doc.trolltech.com/4.5/qabstractitemview.html#setItemDelegate)

TomASS
29th September 2009, 07:40
Thank you,


There you have it, pretty simple.
Yes, that's simple :)


But if you really just want to alternate the row colors, this would be much better.
Yest, that's what I meant.


I almost forgot: you're starting with 1 in both your for-loops. Remember that the TableWidgets indexes start at 0 and end at rowCount - 1. I have corrected that, s.a.
Yest, I know, thank you for your attention.


Of course you can use a delegate with a QTableWidget, it's also part of the model-view architecture.
I've wrote, I fourtunately havent't use model-view-delegate architecture.