Moayyad Yaghi
Moayyad Yaghi

Reputation: 3722

changing cell background color in qt

i'm new to pyqt , and i'm still facing some newbie problems :D
i have a QTableWidget that is item delegated on a QChoice control ( hope i said it right ) i need to have the cell background color changes whenever a user change the choice control selection
briefly: how to change a cell background color in a table widget ??
i use pyqt4 and python 2.6
thanx in advance

Upvotes: 2

Views: 18715

Answers (6)

Wade Wang
Wade Wang

Reputation: 690

For supplement in C++ way, if you want to paint custom color unlike Qt::red and so on, you can do something like : ui->tableWidget->item(i, j)->setBackground(QColor(152,234,112));

Upvotes: 0

AdvancedNewbie
AdvancedNewbie

Reputation: 61

Here are some useful lines of code. Sorry for redundancy, I'm trying to gain some reputation.

QStandardItemModel* model = new QStandardItemModel(numRows, numColumns);
QStringList headers;
headers.append("Date");
model->setHorizontalHeaderLabels(headers);
QStandardItem* item = new QStandardItem(text);
item->setData(Qt::AlignCenter, Qt::TextAlignmentRole);
item->setData(QVariant(QBrush(Qt::green)), Qt::BackgroundRole);
model->setItem(row, column, item);

or simply:

item->setBackground(Qt::green);

Upvotes: 1

cosminq
cosminq

Reputation: 51

if you use QTableView use this:

model.setData(model.index(0, 0), QVariant(QBrush(Qt::red)), Qt::BackgroundRole);

Upvotes: 2

Alexandr Bulanov
Alexandr Bulanov

Reputation: 113

I used something like this:

brush = QtGui.QBrush(QtGui.QColor(255, 0, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
item.setBackground(brush)

Where item is QTableWidgetItem object

Upvotes: 9

Maxim Popravko
Maxim Popravko

Reputation: 4159

Use

QTableWidgetItem QTableWidget.item(row, column)

and

QTableWidgetItem setData(role, data)

with

Qt.BackgroundRole

as follows:

table.item(0, 0).setData(Qt.BackgroundRole, color).

And read about the Roles mechanism used in Qt Model/View.

Upvotes: 4

Naruto
Naruto

Reputation: 9634

Hey, you set the delegate method for the table widget. in the paint event of the delegate you handle the color changing technique.. have a look at this example,here they have done custom selection color. same way you handle the item cell painting

Upvotes: 0

Related Questions