Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How to color a row of qSqlQueryModel where data of cell is smth
Forum Updated to NodeBB v4.3 + New Features

How to color a row of qSqlQueryModel where data of cell is smth

Scheduled Pinned Locked Moved Unsolved General and Desktop
21 Posts 4 Posters 2.5k Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    SimonaBolgradova
    wrote on last edited by
    #1
    class ColorDelegate: public QItemDelegate
    {
        Q_OBJECT
    public:
        QSet<QString> alarmsSet;
        ColorDelegate(QObject *parent = 0) : QItemDelegate(parent) {}
    
    public:
        virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
        {
            drawBackground(painter, option, index);
            QItemDelegate::paint(painter, option, index);
        };
    
    protected:
        virtual void drawBackground(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
        {
    
            //qDebug()<<alarmsSet;
           // foreach (const QString &value, alarmsSet){
    
                 if (index.data() ==damage) {
    
                    painter->fillRect(option.rect, QBrush(Qt::yellow, Qt::SolidPattern));
                }
           // }
    
        }
    
    private:
        QString damage = "Damage";
    
    signals:
    private slots:
        void alarms(QSet<QString> set){
            alarmsSet= set;
        }
    };
    

    When I set this class as ItemDelegate to my qTableView I color a cell with "Damage" data. And this is the result.
    f1b0c416-8287-402d-8de3-f8851d1e50d7-image.png My aim is to color a row with a specific message. I have a slot that provides all the messages that need to be colored but when I use them in drawBackground my QSet is empty.

    How can I do this, why is my QSet empty in drawBackground and is it possible to do it so?

    JonBJ 1 Reply Last reply
    0
    • S SimonaBolgradova
      class ColorDelegate: public QItemDelegate
      {
          Q_OBJECT
      public:
          QSet<QString> alarmsSet;
          ColorDelegate(QObject *parent = 0) : QItemDelegate(parent) {}
      
      public:
          virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
          {
              drawBackground(painter, option, index);
              QItemDelegate::paint(painter, option, index);
          };
      
      protected:
          virtual void drawBackground(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
          {
      
              //qDebug()<<alarmsSet;
             // foreach (const QString &value, alarmsSet){
      
                   if (index.data() ==damage) {
      
                      painter->fillRect(option.rect, QBrush(Qt::yellow, Qt::SolidPattern));
                  }
             // }
      
          }
      
      private:
          QString damage = "Damage";
      
      signals:
      private slots:
          void alarms(QSet<QString> set){
              alarmsSet= set;
          }
      };
      

      When I set this class as ItemDelegate to my qTableView I color a cell with "Damage" data. And this is the result.
      f1b0c416-8287-402d-8de3-f8851d1e50d7-image.png My aim is to color a row with a specific message. I have a slot that provides all the messages that need to be colored but when I use them in drawBackground my QSet is empty.

      How can I do this, why is my QSet empty in drawBackground and is it possible to do it so?

      JonBJ Offline
      JonBJ Offline
      JonB
      wrote on last edited by JonB
      #2

      @SimonaBolgradova said in How to color a row of qSqlQueryModel where data of cell is smth:

      but when I use them in drawBackground my QSet is empty

      why is my QSet empty in drawBackground

      Hello and welcome.

      The code you show has a QSet<QString> alarmsSet member variable, and a slot which assigns this set to a set passed as a parameter to it. Nobody can tell when you call that from the code you show, so nobody can tell you why it is empty.

      if (index.data() ==damage)

      What is this damage variable, which you can compare against the value at an index in the model? Note that this is only looking at one cell. If you want all cells in a row to be drawn a certain way based on the content/value of one cell, you will have to get the other cells to look in that one cell in the row when it is their turn to be drawn in order to dictate how they themselves are to be drawn.

      It might be that using some role value on al cells would be a good way to store how their background is to be shown.

      S 1 Reply Last reply
      0
      • S Offline
        S Offline
        SimonaBolgradova
        wrote on last edited by
        #3

        The slot executes correctly and transfers the data
        and this is my damage variable.

        private:
            QString damage = "Damage";
        
        Gojir4G 1 Reply Last reply
        0
        • S SimonaBolgradova

          The slot executes correctly and transfers the data
          and this is my damage variable.

          private:
              QString damage = "Damage";
          
          Gojir4G Offline
          Gojir4G Offline
          Gojir4
          wrote on last edited by
          #4

          @SimonaBolgradova Instead of a delegate you could use a proxy model.
          here is a simple python example

          class MyModel(QIdentityProxyModel):
              def data(self, proxyIndex: Union[QModelIndex, QPersistentModelIndex], role: int = ...) -> Any:
          
                  if Qt.BackgroundRole == role:
                      v = super().data(proxyIndex, Qt.DisplayRole)
                      if 'Damage' in v:
                          return QColor('yellow')
          
                  return super().data(proxyIndex, role)
          
          1 Reply Last reply
          0
          • JonBJ JonB

            @SimonaBolgradova said in How to color a row of qSqlQueryModel where data of cell is smth:

            but when I use them in drawBackground my QSet is empty

            why is my QSet empty in drawBackground

            Hello and welcome.

            The code you show has a QSet<QString> alarmsSet member variable, and a slot which assigns this set to a set passed as a parameter to it. Nobody can tell when you call that from the code you show, so nobody can tell you why it is empty.

            if (index.data() ==damage)

            What is this damage variable, which you can compare against the value at an index in the model? Note that this is only looking at one cell. If you want all cells in a row to be drawn a certain way based on the content/value of one cell, you will have to get the other cells to look in that one cell in the row when it is their turn to be drawn in order to dictate how they themselves are to be drawn.

            It might be that using some role value on al cells would be a good way to store how their background is to be shown.

            S Offline
            S Offline
            SimonaBolgradova
            wrote on last edited by
            #5

            @JonB 28c7f51d-ab40-460c-aed8-865ccfd88214-image.png

            JonBJ 1 Reply Last reply
            0
            • S SimonaBolgradova

              @JonB 28c7f51d-ab40-460c-aed8-865ccfd88214-image.png

              JonBJ Offline
              JonBJ Offline
              JonB
              wrote on last edited by
              #6

              @SimonaBolgradova
              So you do appear to set the value and your picture shows that you are indeed coloring the "Damage" cell yellow. In which case it seems to behaving as per your code, so what is your question?

              Meanwhile you might prefer to try @Gojir4's suggestion of doing the background coloring from the data() method instead of a delegate. But I'm not sure that has anything to do with whatever your actual question is.

              S 1 Reply Last reply
              0
              • JonBJ JonB

                @SimonaBolgradova
                So you do appear to set the value and your picture shows that you are indeed coloring the "Damage" cell yellow. In which case it seems to behaving as per your code, so what is your question?

                Meanwhile you might prefer to try @Gojir4's suggestion of doing the background coloring from the data() method instead of a delegate. But I'm not sure that has anything to do with whatever your actual question is.

                S Offline
                S Offline
                SimonaBolgradova
                wrote on last edited by
                #7

                @JonB said in How to color a row of qSqlQueryModel where data of cell is smth:

                So you do appear to set the value and your picture shows that you are indeed coloring the "Damage" cell yellow. In which case it seems to behaving as per your code, so what is your question?
                Meanwhile you might prefer to try @Gojir4's suggestion of doing the background coloring from the data() method instead of a delegate. But I'm not sure that has anything to do with whatever your actual question is.

                My question was why when I use alarmsSet in drawnBackgroung is empty set and how to color the whole row.

                And could you show me some simple example with data()

                JonBJ 1 Reply Last reply
                0
                • VRoninV Offline
                  VRoninV Offline
                  VRonin
                  wrote on last edited by VRonin
                  #8

                  You are overcomplicating things, it's super straightforward:

                  class ColorDelegate: public QStyledItemDelegate{
                      Q_OBJECT
                  public:
                      using QStyledItemDelegate::QStyledItemDelegate;
                      const QSet<QString>& alarms() const {return m_alarms;}
                      void setAlarms(const QSet<QString>& alm) {m_alarms=alm;}
                  protected:
                      void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const override{
                          QStyledItemDelegate::initStyleOption(option,index);
                          if(m_alarms.contains(index.data().toString())
                              option->backgroundBrush = QBrush(Qt::yellow, Qt::SolidPattern);
                      }
                  private:
                      QSet<QString> m_alarms;
                  };
                  

                  how to color the whole row.

                  Instead of index.data().toString() use index.sibling(index.row(),ColumnWithAlarms).data().toString()

                  P.S.
                  The data() solution is perfectly valid, I disagree with it only on a philosophical level (philosophy has hardly any place in programming anyway) as the color isn't data, it's a way to paint existing data. At the end of the day, use the solution you find easier

                  "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                  ~Napoleon Bonaparte

                  On a crusade to banish setIndexWidget() from the holy land of Qt

                  S 1 Reply Last reply
                  2
                  • S SimonaBolgradova

                    @JonB said in How to color a row of qSqlQueryModel where data of cell is smth:

                    So you do appear to set the value and your picture shows that you are indeed coloring the "Damage" cell yellow. In which case it seems to behaving as per your code, so what is your question?
                    Meanwhile you might prefer to try @Gojir4's suggestion of doing the background coloring from the data() method instead of a delegate. But I'm not sure that has anything to do with whatever your actual question is.

                    My question was why when I use alarmsSet in drawnBackgroung is empty set and how to color the whole row.

                    And could you show me some simple example with data()

                    JonBJ Offline
                    JonBJ Offline
                    JonB
                    wrote on last edited by JonB
                    #9

                    @SimonaBolgradova said in How to color a row of qSqlQueryModel where data of cell is smth:

                    and how to color the whole row.

                    I already answered this:

                    If you want all cells in a row to be drawn a certain way based on the content/value of one cell, you will have to get the other cells to look in that one cell in the row when it is their turn to be drawn in order to dictate how they themselves are to be drawn.

                    But you do not seem to have acknowledged this.

                    Note that if only the value in the Message column changes you want that to affect the color of all the other cells in that row. It is your responsibility to tell the view that those other cells have changed and need their color to be redrawn (else it will only do the Message column in the row), e.g. via a suitable dataChanged() signal. Although @VRonin mentions sibling() in his code he does not seem to have pointed out that you will need to cause the redraw in those columns?

                    VRoninV 1 Reply Last reply
                    1
                    • JonBJ JonB

                      @SimonaBolgradova said in How to color a row of qSqlQueryModel where data of cell is smth:

                      and how to color the whole row.

                      I already answered this:

                      If you want all cells in a row to be drawn a certain way based on the content/value of one cell, you will have to get the other cells to look in that one cell in the row when it is their turn to be drawn in order to dictate how they themselves are to be drawn.

                      But you do not seem to have acknowledged this.

                      Note that if only the value in the Message column changes you want that to affect the color of all the other cells in that row. It is your responsibility to tell the view that those other cells have changed and need their color to be redrawn (else it will only do the Message column in the row), e.g. via a suitable dataChanged() signal. Although @VRonin mentions sibling() in his code he does not seem to have pointed out that you will need to cause the redraw in those columns?

                      VRoninV Offline
                      VRoninV Offline
                      VRonin
                      wrote on last edited by VRonin
                      #10

                      @JonB said in How to color a row of qSqlQueryModel where data of cell is smth:

                      does not seem to have pointed out that you will need to cause the redraw in those columns?

                      Excellent spot as always!

                      connect(model,QAbstractItemModel::dataChanged,view,[=](const QModelIndex &topLeft, const QModelIndex &bottomRight, const QList<int> &roles){
                          if(!roles.isEmpty() && !roles.contains(Qt::DisplayRole))
                              return;
                          if(ColumnWithAlarms < topLeft.column() || ColumnWithAlarms > bottomRight.column())
                              return;
                          view->update();
                      });
                      

                      "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                      ~Napoleon Bonaparte

                      On a crusade to banish setIndexWidget() from the holy land of Qt

                      1 Reply Last reply
                      2
                      • VRoninV VRonin

                        You are overcomplicating things, it's super straightforward:

                        class ColorDelegate: public QStyledItemDelegate{
                            Q_OBJECT
                        public:
                            using QStyledItemDelegate::QStyledItemDelegate;
                            const QSet<QString>& alarms() const {return m_alarms;}
                            void setAlarms(const QSet<QString>& alm) {m_alarms=alm;}
                        protected:
                            void initStyleOption(QStyleOptionViewItem *option, const QModelIndex &index) const override{
                                QStyledItemDelegate::initStyleOption(option,index);
                                if(m_alarms.contains(index.data().toString())
                                    option->backgroundBrush = QBrush(Qt::yellow, Qt::SolidPattern);
                            }
                        private:
                            QSet<QString> m_alarms;
                        };
                        

                        how to color the whole row.

                        Instead of index.data().toString() use index.sibling(index.row(),ColumnWithAlarms).data().toString()

                        P.S.
                        The data() solution is perfectly valid, I disagree with it only on a philosophical level (philosophy has hardly any place in programming anyway) as the color isn't data, it's a way to paint existing data. At the end of the day, use the solution you find easier

                        S Offline
                        S Offline
                        SimonaBolgradova
                        wrote on last edited by
                        #11

                        @VRonin how to get alarms from my slot

                        private slots:
                           void alarms(QSet<QString> set){
                               setAlarms(set);
                           }
                        

                        Is it smth like that?
                        and why I have this error
                        f20316f6-4131-4991-9b39-ee6d62d31744-image.png

                        JonBJ 1 Reply Last reply
                        0
                        • S SimonaBolgradova

                          @VRonin how to get alarms from my slot

                          private slots:
                             void alarms(QSet<QString> set){
                                 setAlarms(set);
                             }
                          

                          Is it smth like that?
                          and why I have this error
                          f20316f6-4131-4991-9b39-ee6d62d31744-image.png

                          JonBJ Offline
                          JonBJ Offline
                          JonB
                          wrote on last edited by
                          #12

                          @SimonaBolgradova said in How to color a row of qSqlQueryModel where data of cell is smth:

                          how to get alarms from my slot

                          Don't know what this means.

                          and why I have this error

                          Start with how can the method be const if it alters m_alarms? [ @VRonin ?? :) ]

                          VRoninV 1 Reply Last reply
                          1
                          • JonBJ JonB

                            @SimonaBolgradova said in How to color a row of qSqlQueryModel where data of cell is smth:

                            how to get alarms from my slot

                            Don't know what this means.

                            and why I have this error

                            Start with how can the method be const if it alters m_alarms? [ @VRonin ?? :) ]

                            VRoninV Offline
                            VRoninV Offline
                            VRonin
                            wrote on last edited by
                            #13

                            @JonB said in How to color a row of qSqlQueryModel where data of cell is smth:

                            Start with how can the method be const if it alters m_alarms? [ @VRonin ?? :) ]

                            Yep, corrected.

                            P.S.
                            In most use cases you don't need a slot. Using Qt5 connections you can connect directly to the setAlarms method

                            "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                            ~Napoleon Bonaparte

                            On a crusade to banish setIndexWidget() from the holy land of Qt

                            1 Reply Last reply
                            1
                            • S Offline
                              S Offline
                              SimonaBolgradova
                              wrote on last edited by
                              #14

                              m_alarms keeps to be empty :(
                              I connected like that in another class named Controller

                              connect(
                                      s, &SQLQueries::alarms,
                                      d, &ColorDelegate::setAlarms
                                  );
                              

                              Alarms signal will be emitted when I triggered action on and m_alarms get some values but then in initStyleOption m_alarms is empty.
                              aec675a0-49a6-477b-ba66-4b26404dc406-image.png

                              1 Reply Last reply
                              0
                              • VRoninV Offline
                                VRoninV Offline
                                VRonin
                                wrote on last edited by
                                #15

                                Can you show us the code where you set the delegate on the view?

                                "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                                ~Napoleon Bonaparte

                                On a crusade to banish setIndexWidget() from the holy land of Qt

                                S 1 Reply Last reply
                                0
                                • VRoninV VRonin

                                  Can you show us the code where you set the delegate on the view?

                                  S Offline
                                  S Offline
                                  SimonaBolgradova
                                  wrote on last edited by
                                  #16

                                  @VRonin

                                  void MainWindow::setTable(QSqlQueryModel * model)
                                  {
                                     ui->tableView->setModel( model );
                                     ui->tableView->setItemDelegate(new ColorDelegate(ui->tableView));
                                  
                                     ui->tableView->resizeColumnsToContents();
                                  }
                                  
                                  VRoninV 1 Reply Last reply
                                  0
                                  • S SimonaBolgradova

                                    @VRonin

                                    void MainWindow::setTable(QSqlQueryModel * model)
                                    {
                                       ui->tableView->setModel( model );
                                       ui->tableView->setItemDelegate(new ColorDelegate(ui->tableView));
                                    
                                       ui->tableView->resizeColumnsToContents();
                                    }
                                    
                                    VRoninV Offline
                                    VRoninV Offline
                                    VRonin
                                    wrote on last edited by
                                    #17

                                    @SimonaBolgradova said in How to color a row of qSqlQueryModel where data of cell is smth:

                                    ui->tableView->setItemDelegate(new ColorDelegate(ui->tableView));

                                    Fire and forget pointer. The delegate you are connecting is not the one used by the view then. what is d in d, &ColorDelegate::setAlarms?

                                    It should be something like:

                                    auto alarmDelegate = new ColorDelegate(ui->tableView);
                                    ui->tableView->setItemDelegate(alarmDelegate);
                                    connect(s, &SQLQueries::alarms, alarmDelegate, &ColorDelegate::setAlarms);
                                    

                                    "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                                    ~Napoleon Bonaparte

                                    On a crusade to banish setIndexWidget() from the holy land of Qt

                                    S 1 Reply Last reply
                                    2
                                    • VRoninV VRonin

                                      @SimonaBolgradova said in How to color a row of qSqlQueryModel where data of cell is smth:

                                      ui->tableView->setItemDelegate(new ColorDelegate(ui->tableView));

                                      Fire and forget pointer. The delegate you are connecting is not the one used by the view then. what is d in d, &ColorDelegate::setAlarms?

                                      It should be something like:

                                      auto alarmDelegate = new ColorDelegate(ui->tableView);
                                      ui->tableView->setItemDelegate(alarmDelegate);
                                      connect(s, &SQLQueries::alarms, alarmDelegate, &ColorDelegate::setAlarms);
                                      
                                      S Offline
                                      S Offline
                                      SimonaBolgradova
                                      wrote on last edited by
                                      #18

                                      @VRonin

                                      Fire and forget pointer. The delegate you are connecting is not the one used by the view then. what is d in d, &ColorDelegate::setAlarms?

                                      in controller.h

                                      private:
                                      ColorDelegate * d = new ColorDelegate();
                                      

                                      It should be something like:

                                      auto alarmDelegate = new ColorDelegate(ui->tableView);
                                      ui->tableView->setItemDelegate(alarmDelegate);
                                      connect(s, &SQLQueries::alarms, alarmDelegate, &ColorDelegate::setAlarms);
                                      

                                      this doesn't work and all fields are empty in my QTableView

                                      S 1 Reply Last reply
                                      0
                                      • S SimonaBolgradova

                                        @VRonin

                                        Fire and forget pointer. The delegate you are connecting is not the one used by the view then. what is d in d, &ColorDelegate::setAlarms?

                                        in controller.h

                                        private:
                                        ColorDelegate * d = new ColorDelegate();
                                        

                                        It should be something like:

                                        auto alarmDelegate = new ColorDelegate(ui->tableView);
                                        ui->tableView->setItemDelegate(alarmDelegate);
                                        connect(s, &SQLQueries::alarms, alarmDelegate, &ColorDelegate::setAlarms);
                                        

                                        this doesn't work and all fields are empty in my QTableView

                                        S Offline
                                        S Offline
                                        SimonaBolgradova
                                        wrote on last edited by
                                        #19

                                        @SimonaBolgradova maybe the problem is that my connection was created in the Controller class. There I create an instance of ColorDelegate and m_alarms is still empty. But how could I connect two classes into another without creating an instance?

                                        1 Reply Last reply
                                        0
                                        • VRoninV Offline
                                          VRoninV Offline
                                          VRonin
                                          wrote on last edited by VRonin
                                          #20

                                          What you are doing at the moment is int a=0; int b=3; and asking why a is 0 and not 3. They are the same type (int) but 2 different objects. You need to call setAlarms on the same object as the one used in the view.

                                          But how could I connect two classes into another without creating an instance?

                                          This question is asked weekly if not daily in this forum just search for "connecting to class". The short answer is that you should structure your app as a tree where the leaves are connected by the branches

                                          "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
                                          ~Napoleon Bonaparte

                                          On a crusade to banish setIndexWidget() from the holy land of Qt

                                          S 1 Reply Last reply
                                          2

                                          • Login

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved