How to format negative number as red colour in QTableWidget?



  • How do we format the QTableWidget such that negative numbers appear as red in colour



  • 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);
            }
          }
        }
      });
    
    


  • @VRonin Thanks.
    This needs to be done in the python code? and is it possible to implement the same functionality using Qt style sheet?


  • Qt Champions 2016

    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.



  • 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 first if as it's just optimisation) and connect the dataChanged signal of tableWidget.model() to it

    and is it possible to implement the same functionality using Qt style sheet?

    Not alone and it would be a lot of work


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.