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 use QTableView & Model
Forum Updated to NodeBB v4.3 + New Features

How to use QTableView & Model

Scheduled Pinned Locked Moved Unsolved General and Desktop
qtableview
26 Posts 3 Posters 12.3k 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.
  • A Offline
    A Offline
    alex_malyu
    wrote on last edited by alex_malyu
    #2

    @cherple said:

    class mygrid_widget : public QAbstractTableModel

    Do not confuse yourself mygrid_widget has nothing to do with widget.
    It is supposed to be a subclass of QAbstractTableModel. And as such should
    implement certain methods which you either did not implement (why in this case it even compiles?) or did not show its implementation.

    " When subclassing QAbstractTableModel, you must implement rowCount(), columnCount(), and data(). " see
    http://doc.qt.io/qt-5/qabstracttablemodel.html#details

    If you did not implement setData do not use it.
    QTableView you create is not within any layout and is not even shown.

    I suggest;

    • create a widget which which will show table view. Go through Qt examples if you have problem with it.
    • Subclass QAbstractTableModel implement columnCount(...) and rowCount (...) and data(...).

    You do not need setData if you do not have editable model all you need to to implement data that it returns proper value with displayRole,
    Again there are enough examples In Qt.

    1 Reply Last reply
    1
    • C Offline
      C Offline
      cherple
      wrote on last edited by
      #3

      Hi, thanks for the prompt reply. Yes I have row and column count as well as data inplemented. I managed to display the table.

      But I have another question. So how do I set the values in the cell? Is there some function I can use that I do not know of, or do I have to create my own 2D array and store the values inside, then return the values within the data() function?

      1 Reply Last reply
      0
      • A Offline
        A Offline
        alex_malyu
        wrote on last edited by alex_malyu
        #4

        data(..) function you have to implement supposed to return values as QVariant . Take them from your array, add member array or compute on the fly depending on your needs.

        QVariant MyModel::data(const QModelIndex &index, int role) const
        {
        if (!index.isValid())
        return QVariant();

        if (role == Qt::DisplayRole )
        {
        if ( (row/2)*2 == row )
        return QVariant( row );
        else
        return QVariant( 5);
        }

        return QVariant();
        }

        1 Reply Last reply
        1
        • C Offline
          C Offline
          cherple
          wrote on last edited by
          #5

          I'd also like to confirm one point. When is data() called? Only on startup and when the cells are modified? My issue now is performance issue. I put a debug statement within my data() function, and I see that everytime I mouse over or out of my tableview, all the cells will call the data function and generates a lag.. Everytime I click on a single cell all the cells also updates..

          A 1 Reply Last reply
          0
          • C Offline
            C Offline
            cherple
            wrote on last edited by
            #6

            Is it also possible to have two different select colors? And how do I do that? You know when you select a cell, the selected color can be set using a style sheet, but since I'm using table view, I was wondering if my view can query my model. For example I have a variable that stores the selection. If user selects a value "1", when he select a cell it will be red color, when he select "2" form the drop down list, when he selects the cell it will be blue. Is that possible?(my table will display two different selected cell colors at the same time, because the different colors are supposed to have a different meaning)

            1 Reply Last reply
            0
            • B Offline
              B Offline
              bsomervi
              wrote on last edited by
              #7

              Before going too far down the path of a custom model you might try QStandardItemModel as it provides all the capability you have described using an existing Qt model that is designed to hold user data and attributes of that data such as font, background and foreground brushes, ...

              The key point being that if you do not need a complex underlying data storage or generation model for your model data then QStandardItemModel saves a lot of complexity.

              1 Reply Last reply
              0
              • C Offline
                C Offline
                cherple
                wrote on last edited by
                #8

                What about the refresh rate of the tableview? Meaning when is data() called? Why is it that everytime I mouse over or out, or clicking on a cell, data() will be called for all of the cells? This is extremely crucial as it seriously affects performance.. I need it to be realtime

                1 Reply Last reply
                0
                • C cherple

                  I'd also like to confirm one point. When is data() called? Only on startup and when the cells are modified? My issue now is performance issue. I put a debug statement within my data() function, and I see that everytime I mouse over or out of my tableview, all the cells will call the data function and generates a lag.. Everytime I click on a single cell all the cells also updates..

                  A Offline
                  A Offline
                  alex_malyu
                  wrote on last edited by alex_malyu
                  #9

                  @cherple

                  data(...) is called every time cell has to be re-drawn.
                  Even though it is always a good idea to keep your code robust it may be as fast as simple returning array value at specified index and is not going to cause any visible delay cause drawing cell will be always slower.

                  Remove your debug statements from there and you will see no delays there if you do not do complex computation within it.

                  Mentioned by bsomervi QStandardItemModel to my mind is too heavy if you want simply display predefined data. But most of the time , especially if your code would run only on desktops with relatively small number of rows/columns you will not notice any difference.

                  B 1 Reply Last reply
                  1
                  • C Offline
                    C Offline
                    cherple
                    wrote on last edited by
                    #10

                    Oh wow! I didn't know the debug statement uses so much resource.. Speed wise is all good now, still a little slower with the widget but definitely a lot faster as compared to previously. Thanks! :))

                    But how would u suggest I do this then? I will have a variable to store a users selection from a drop down list, then based on this variable's value, when a user selects a cell it should appear as a different color, probably from a predefined set of colors.

                    For example: 0=red,1=blue,2=green
                    So when user picked 1, and select a cell, the cell within be blue, then the user proceed with choosing 2, then select the cell next to it, and that cell should be green. So you should see the two boxes side by side one being blue and one being green.

                    A 1 Reply Last reply
                    0
                    • A alex_malyu

                      @cherple

                      data(...) is called every time cell has to be re-drawn.
                      Even though it is always a good idea to keep your code robust it may be as fast as simple returning array value at specified index and is not going to cause any visible delay cause drawing cell will be always slower.

                      Remove your debug statements from there and you will see no delays there if you do not do complex computation within it.

                      Mentioned by bsomervi QStandardItemModel to my mind is too heavy if you want simply display predefined data. But most of the time , especially if your code would run only on desktops with relatively small number of rows/columns you will not notice any difference.

                      B Offline
                      B Offline
                      bsomervi
                      wrote on last edited by
                      #11

                      @alex_malyu What is so heavyweight?

                      #include <QApplication>
                      #include <QString>
                      #include <QStandardItemModel>
                      #include <QtWidgets>
                      #include <QDebug>
                      
                      int main (int argc, char * argv[]) {
                        QApplication app {argc, argv};
                        QStandardItemModel model;
                        model.appendRow (QList<QStandardItem *> {
                            new QStandardItem {QStringLiteral ("item 1")}
                            , new QStandardItem {QStringLiteral ("item 2")}
                            , new QStandardItem {QStringLiteral ("item 3")}});
                        auto yellow_item = new QStandardItem {QStringLiteral ("item 4")};
                        yellow_item->setBackground (Qt::yellow);
                        model.appendRow (QList<QStandardItem *> {
                            yellow_item
                            , new QStandardItem {QStringLiteral ("item 5")}
                            , new QStandardItem {QStringLiteral ("item 6")}});
                        model.connect (&model, &QStandardItemModel::itemChanged, [] (QStandardItem *item) {
                            qDebug () << QStringLiteral ("item(%1, %2) value[%3]")
                      	.arg (item->row ())
                      	.arg (item->column ())
                      	.arg (item->text ());
                          });
                        QTableView view;
                        view.setModel (&model);
                        view.connect (&view, &QTableView::clicked, [&model] (QModelIndex const& index) {
                            auto * item = model.itemFromIndex (index);
                            qDebug () << QStringLiteral ("item(%1, %2) value[%3] clicked")
                      	.arg (item->row ())
                      	.arg (item->column ())
                      	.arg (item->text ());
                          });
                        view.show ();
                        QObject::connect (&app, &QApplication::lastWindowClosed, &app, &QApplication::quit);
                        return app.exec ();
                      }
                      
                      A 1 Reply Last reply
                      0
                      • B bsomervi

                        @alex_malyu What is so heavyweight?

                        #include <QApplication>
                        #include <QString>
                        #include <QStandardItemModel>
                        #include <QtWidgets>
                        #include <QDebug>
                        
                        int main (int argc, char * argv[]) {
                          QApplication app {argc, argv};
                          QStandardItemModel model;
                          model.appendRow (QList<QStandardItem *> {
                              new QStandardItem {QStringLiteral ("item 1")}
                              , new QStandardItem {QStringLiteral ("item 2")}
                              , new QStandardItem {QStringLiteral ("item 3")}});
                          auto yellow_item = new QStandardItem {QStringLiteral ("item 4")};
                          yellow_item->setBackground (Qt::yellow);
                          model.appendRow (QList<QStandardItem *> {
                              yellow_item
                              , new QStandardItem {QStringLiteral ("item 5")}
                              , new QStandardItem {QStringLiteral ("item 6")}});
                          model.connect (&model, &QStandardItemModel::itemChanged, [] (QStandardItem *item) {
                              qDebug () << QStringLiteral ("item(%1, %2) value[%3]")
                        	.arg (item->row ())
                        	.arg (item->column ())
                        	.arg (item->text ());
                            });
                          QTableView view;
                          view.setModel (&model);
                          view.connect (&view, &QTableView::clicked, [&model] (QModelIndex const& index) {
                              auto * item = model.itemFromIndex (index);
                              qDebug () << QStringLiteral ("item(%1, %2) value[%3] clicked")
                        	.arg (item->row ())
                        	.arg (item->column ())
                        	.arg (item->text ());
                            });
                          view.show ();
                          QObject::connect (&app, &QApplication::lastWindowClosed, &app, &QApplication::quit);
                          return app.exec ();
                        }
                        
                        A Offline
                        A Offline
                        alex_malyu
                        wrote on last edited by alex_malyu
                        #12

                        @bsomervi said:

                        new QStandardItem {QStringLiteral ("item 1")}

                        Simplicity of usage has nothing to do with complexity of implementation or memory used and efficiency in general.
                        When you have values already stored somewhere and all you need is to return the specific value does not make any sense create an additional array or do any additional memory allocation etc.
                        Functionality provided by QStandardItemModel is not needed for such trivial tasks.
                        All you need is to return value.
                        With the same results you could suggest to use QTableWidget.
                        Or better example - you are not using stl vector when using one variable is sufficient.
                        Do not take it as an offence.

                        1 Reply Last reply
                        0
                        • C cherple

                          Oh wow! I didn't know the debug statement uses so much resource.. Speed wise is all good now, still a little slower with the widget but definitely a lot faster as compared to previously. Thanks! :))

                          But how would u suggest I do this then? I will have a variable to store a users selection from a drop down list, then based on this variable's value, when a user selects a cell it should appear as a different color, probably from a predefined set of colors.

                          For example: 0=red,1=blue,2=green
                          So when user picked 1, and select a cell, the cell within be blue, then the user proceed with choosing 2, then select the cell next to it, and that cell should be green. So you should see the two boxes side by side one being blue and one being green.

                          A Offline
                          A Offline
                          alex_malyu
                          wrote on last edited by
                          #13

                          @cherple said:

                          But how would u suggest I do this then? I will have a variable to store a users selection from a drop down list, then based on this variable's value, when a user selects a cell it should appear as a different color, probably from a predefined set of colors.

                          For example: 0=red,1=blue,2=green
                          So when user picked 1, and select a cell, the cell within be blue, then the user proceed with choosing 2, then select the cell next to it, and that cell should be green. So you should see the two boxes side by side one being blue and one being green.

                          To specify color you need in the in the same data(... ) handle Qt::DecorationRole
                          I will assume you already know value (v) below:

                          int v =....
                          if (role == Qt::DecorationRole)
                          {
                          if ( v == 0 )
                          return QVariant(QColor(Qt::red));
                          else if( .... )
                          ....
                          else
                          ,,, ;
                          }

                          .........

                          1 Reply Last reply
                          0
                          • C Offline
                            C Offline
                            cherple
                            wrote on last edited by
                            #14

                            Well I tried the decoration role, but all the cells are now red. I want only cells to become red when I select them. Also, all the boxes have a checkbox inside them now.

                            A 1 Reply Last reply
                            0
                            • C cherple

                              Well I tried the decoration role, but all the cells are now red. I want only cells to become red when I select them. Also, all the boxes have a checkbox inside them now.

                              A Offline
                              A Offline
                              alex_malyu
                              wrote on last edited by alex_malyu
                              #15

                              @cherple

                              You had to return color you wanted depending on a row, column or value.
                              I returned red as an example.

                              As for check status you probably handle more than Qt::DisplayRole and Qt::DecorationRole.
                              From the top of my head it might be Qt::CheckStateRole

                              Post code of your data(...) function.

                              1 Reply Last reply
                              0
                              • C Offline
                                C Offline
                                cherple
                                wrote on last edited by
                                #16

                                This is my data:

                                if (role == Qt::DisplayRole)
                                {
                                Return data[row][col];
                                }
                                Else if (role = Qt::DecorationRole)
                                {
                                //if ( selectionVar == 0 )
                                return QVariant(QColor(Qt::red));
                                //else if( .... )
                                }

                                For now I just wanted to test the functionality so I just set it as red irregardless of my selection mode. I wanted to see if only my selected cell will be red.. But all the cells become a checkbox with red back ground.. I tried the checkstaterole before and it's the same.. The cells become a check box with the colored background.. I will try to take a screenshot later

                                A 1 Reply Last reply
                                0
                                • C cherple

                                  This is my data:

                                  if (role == Qt::DisplayRole)
                                  {
                                  Return data[row][col];
                                  }
                                  Else if (role = Qt::DecorationRole)
                                  {
                                  //if ( selectionVar == 0 )
                                  return QVariant(QColor(Qt::red));
                                  //else if( .... )
                                  }

                                  For now I just wanted to test the functionality so I just set it as red irregardless of my selection mode. I wanted to see if only my selected cell will be red.. But all the cells become a checkbox with red back ground.. I tried the checkstaterole before and it's the same.. The cells become a check box with the colored background.. I will try to take a screenshot later

                                  A Offline
                                  A Offline
                                  alex_malyu
                                  wrote on last edited by alex_malyu
                                  #17

                                  @cherple

                                  I am a bit surprised handling decoration role has such effect (checkbox),
                                  bu t I believe overriding
                                  virtual Qt::ItemFlags flags ( const QModelIndex & index ) const
                                  should solve it. Something like :

                                  Qt::ItemFlags myClass::flags ( const QModelIndex & index ) const
                                  {
                                  return Qt::ItemIsSelectable|Qt::ItemIsEnabled; // make sure not to return Qt::ItemIsUserCheckable
                                  }

                                  As for color, model can define cell color, but it does not have any idea what is selected in specific view.

                                  So, if you want to change color of only selected cell you need to do it on QTableView level.
                                  Or at least you can let model know that this cell is selected and need custom color every time
                                  selection is changed. For example add array or map which will keep color per cell and set values there, use this container in data to define cell color.
                                  In this case it had to be used with a single view, but I do not think it is a problem for you.

                                  1 Reply Last reply
                                  0
                                  • C Offline
                                    C Offline
                                    cherple
                                    wrote on last edited by
                                    #18

                                    I'm unable to link the image at the moment. I've reimplemented the flags function as u suggested but it remains the same. In my cell, there will be a check box on the left and the whole cell will be painted red.

                                    Just to confirm, all I had to do was to include the flags function in my model's header file and the flags function in the cpp right? I'm not sure why this is happening :/

                                    1 Reply Last reply
                                    0
                                    • C Offline
                                      C Offline
                                      cherple
                                      wrote on last edited by
                                      #19

                                      This is what i see, and what i typed. I have also included the Flags function as u mentioned(not shown).

                                      Code
                                      Result

                                      1 Reply Last reply
                                      0
                                      • A Offline
                                        A Offline
                                        alex_malyu
                                        wrote on last edited by alex_malyu
                                        #20

                                        Sorry that was my fault - DecorationRole displays icon/picmap.
                                        So these are not checkboxes.

                                        Replace Qt::DecorationRole with role == Qt::BackgroundColorRole.
                                        Something like:

                                        QVariant MyModel::data ( const QModelIndex & index, int role )  const
                                        {
                                        	if ( index.isValid() )
                                        	{
                                        		if( role == Qt::DisplayRole )
                                        		{
                                        			QString str = QString("%1:%2").arg (index.row()).arg (index.column());
                                        			return QVariant( str );
                                        		}
                                        		else if( role == Qt::BackgroundColorRole )
                                        		{
                                        			if( index.row() == index.column() )
                                        				return QVariant(QColor(Qt::red));
                                        			else if( index.row() < index.column() )
                                        				return QVariant(QColor(Qt::yellow));
                                        			else 
                                        				return QVariant(QColor(Qt::green));
                                        		}
                                        
                                        	}
                                        	return QVariant();
                                        }
                                        

                                        And you do not need flags anymore.

                                        1 Reply Last reply
                                        0
                                        • C Offline
                                          C Offline
                                          cherple
                                          wrote on last edited by
                                          #21

                                          No worries, it isn't your fault, because I tried backgroundcolorrole and it returned the same results before.

                                          After entering ur code, this is what it looks like:
                                          http://img.photobucket.com/albums/v483/dragonlancer/D6781CF8-2598-46CA-9290-167CB12FF98C.jpg
                                          The code:
                                          http://img.photobucket.com/albums/v483/dragonlancer/64707ED7-6081-466D-AE35-48263E2A959D.jpg
                                          My table view settings:
                                          http://img.photobucket.com/albums/v483/dragonlancer/74A8A89E-97ED-4A1F-8E68-92AF0101CFA9.jpg

                                          1 Reply Last reply
                                          0

                                          • Login

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