How to format negative number as red colour in QTableWidget?
-
Something like:
QObject::connect(tableWidget->model(), &QAbstractItemModel::dataChanged, [ = ](const QModelIndex & topLeft, const QModelIndex & bottomRight, const QVector<int>& roles)->void{ if(!roles.isEmpty() && !roles.contains(Qt::DisplayRole)) return; const QVariant redBrush = QVariant::fromValue(QBrush(Qt::red)); for(int i = topLeft.row(); i <= bottomRight.row(); ++i) { for(int j = topLeft.column(); j <= bottomRight.column(); ++j) { const QModelIndex currIdx = tableWidget->model()->index(i, j, topLeft.parent()); if(currIdx.data(Qt::DisplayRole).toDouble() < 0.0) { if(currIdx.data(Qt::ForegroundRole) != redBrush) { tableWidget->model()->setData(currIdx, redBrush , Qt::ForegroundRole); } } else if(currIdx.data(Qt::ForegroundRole).isValid()) { tableWidget->model()->setData(currIdx, QVariant(), Qt::ForegroundRole); } } } });
-
Something like:
QObject::connect(tableWidget->model(), &QAbstractItemModel::dataChanged, [ = ](const QModelIndex & topLeft, const QModelIndex & bottomRight, const QVector<int>& roles)->void{ if(!roles.isEmpty() && !roles.contains(Qt::DisplayRole)) return; const QVariant redBrush = QVariant::fromValue(QBrush(Qt::red)); for(int i = topLeft.row(); i <= bottomRight.row(); ++i) { for(int j = topLeft.column(); j <= bottomRight.column(); ++j) { const QModelIndex currIdx = tableWidget->model()->index(i, j, topLeft.parent()); if(currIdx.data(Qt::DisplayRole).toDouble() < 0.0) { if(currIdx.data(Qt::ForegroundRole) != redBrush) { tableWidget->model()->setData(currIdx, redBrush , Qt::ForegroundRole); } } else if(currIdx.data(Qt::ForegroundRole).isValid()) { tableWidget->model()->setData(currIdx, QVariant(), Qt::ForegroundRole); } } } });
-
Hi
it needs to be done in your code.
it sets up a slot ( the lambda) to react to dataChanged signal from the model ( when view saves new value)Its not possible via style sheet as far as i know as it cant read the cell values.
-
@VRonin Thanks.
This needs to be done in the python code? and is it possible to implement the same functionality using Qt style sheet?This needs to be done in the python code?
the part from
[ = ]
onward is a slot. you just have to declare a private slot in your class with that body (the translation to python should be straightforward. you can remove the QVector argument and the firstif
as it's just optimisation) and connect thedataChanged
signal oftableWidget.model()
to itand is it possible to implement the same functionality using Qt style sheet?
Not alone and it would be a lot of work