Insert fill circle into cell of QTableWidget



  • There are too many classes to just paint a circle in a cell. There is no other way?


  • Lifetime Qt Champion

    @juaniyoalm
    Well you can also add the circle as an icon to the cell.
    If you add blank text, the effect is similar.

    alt text

    However, how big do u need the circle to be ?
    It cannot be bigger than the cell height in any case.

    Update: this was just to answer if there was alternatives.
    However, a delegate is far better for it.


  • Lifetime Qt Champion

    You need one class: the delegate.

    In this example they have two if you take the custom editor that you likely don't need.


  • Lifetime Qt Champion

    Hi
    Adding to SGaist . Its not as bad as it looks.
    For a paint circle only delegate, you need very little code.

    #include <QStyledItemDelegate>
    #include <QPainter>
    
    class CircleDelegate: public QStyledItemDelegate {
     protected:
      void paint(QPainter* painter, const QStyleOptionViewItem& opt, const QModelIndex& index) const {
    
        // set brush to green if selected else blue ( not needed just for fun)
        if (opt.state & QStyle::State_Selected) {
          painter->setBrush(Qt::green);
        } else {
          painter->setBrush(Qt::blue);
        }
    
        // paint a circle
        int CircleSize=10;
        painter->drawEllipse(opt.rect.center(), CircleSize, CircleSize);
      }
    };
    

    and you set it to the table by
    ui->tableWidget->setItemDelegateForColumn(1, new CircleDelegate());
    the 1 is the col where u want it

    alt text

    You will need to read over
    http://doc.qt.io/qt-5/model-view-programming.html
    mostly section Item roles
    as to make circle dynamic in size, you can use
    a Qt::UserRole and setData.
    so the size comes from the model.


  • Qt Champions 2018

    Just a couple of small addition to @mrjj 's code:

    • you'll probably also need to reimplement sizeHint() to return a size appropriate to contain the circle.
    • blindly modifying the painter argument is risky. You should call painter->save(); before setting the brush and painter->restore(); after you finished the painting


  • Thank you, the solution is good for me!!! but I would like that the background of cells is fill too. This colour have to change too.
    I thought about inserting a rectangle but I would need the circle to be located on top...


  • Lifetime Qt Champion

    @juaniyoalm
    Hi
    Just use other paint methods like
    painter->drawRect(opt.rect);



  • @mrjj Thank you so much!!

    Okay, I have that solved.

    Another question is that the size of each circle depends on a value that my mushroom class has. In my class I created a paint method but I do not know how to link that method with the delegate or what is the way to write the method.


  • Lifetime Qt Champion

    @juaniyoalm
    Hi, is the value in the model ?
    The delegate can use values from model.
    so the color and size of circle could come from model.



  • @mrjj

    No, that value is in a c++class. I have to create a custom model... It's ok?? Or I can use a default model??


  • Lifetime Qt Champion

    @juaniyoalm
    You can use http://doc.qt.io/qt-5/qstandarditemmodel.html
    if it is. dont have to be custom.
    I though you already had a model ?
    Also is this with a QTableWidget ?
    (it uses a model already )



  • @mrjj

    No, I use QTableView.

    I used a model to try but I don't know how to implement it


  • Lifetime Qt Champion

    @juaniyoalm
    Super. With view its much easier.
    so you have to construct a model with the data
    that comes from the class.
    Did you make a qstandarditemmodel before ?



  • @mrjj
    Yes, I did but without data class



  • @mrjj
    Do you show me how to make??


  • Lifetime Qt Champion

    @juaniyoalm
    Hi
    Please read about userRoles and setData

    http://doc.qt.io/qt-5/model-view-programming.html
    section Item roles

    you can simply put the color / size in user role, or you can have
    it directly as an item in your model.
    Both ways are fine.
    Then delegate read the user role and use the data.



  • I read it and I have tried it but my problem is that size circle depends that value of class and colour of background another value of class. I don't know how do it...


  • Lifetime Qt Champion

    @juaniyoalm
    Hi
    Well the delegate cannot go read into other external classes.
    So you have to at some point take the values from the classes and
    put into the model.
    How often does those values change in the classes ?



  • @mrjj

    The parameters will change very often. There will be hundreds of instances of the class and the values ​​will change.


  • Lifetime Qt Champion

    The problem is not in the number of instances but rather how you access them.

    How are you currently handling these differed classes ?



  • @mrjj @SGaist Hi!!

    The program will be a simulation of the habitat of fungus and fungivores. I have a world class, which contains a matrix (world), and an array of fungivores. The matrix is composed of cell. The cell class contains an array of fungivores (fungivores that are in that cell) and an int that represents the amount of fungus there is. In the course of the execution the value of fungus and the number of fungivores that there will be in each cell will change. That's what I have to represent in the UI. The amount of fungus will represent it by painting the green cells, with an intensity between 0 and 255, depending on the value, and the amount of fungivors will represent it with a circle, the size of the circle will depend on the value. Once I have this sequential version, I will have to make a parallel version.



  • @juaniyoalm
    So can you keep those fungus-intensity-ints in (a column in) your model? Then your view can access it.


  • Lifetime Qt Champion

    Is the matrix a two dimensional table ?



  • @SGaist
    Yes, in each cell there is fungus (int value) and fungivores (array of fungivores).

    I've tried pass QPair or Qlist to QStandarItemModel but is not posible cast to qvariant


  • Lifetime Qt Champion

    What are you currently using to store that "matrix" ?



  • Vector<Vector<Cell>>



  • Some answer please???


  • Lifetime Qt Champion

    Please show some patience and allow 24 hours to run before bumping your own thread. This is a community forum where people answer on their own time. They might not even live in the same timezone as you.

    As for your current trouble. You can build a QAbstractTableModel that will give access to your matrix. For the specific members of your Cell class, you can use custom roles.



  • @SGaist

    I'm sorry, it was my vacation day and I wanted to move forward with the project. I'm sorry.

    To assign the matrix to the model simply the model creates a variable of the same type as the matrix and initialize the model I assign it in some way, is it correct? I do not understand the roles very well ...


  • Lifetime Qt Champion

    You should also provide APIs that will allow you ton modify that matrix.

    As for the roles, they are there to retrieve specific information from the model's elements.



  • @SGaist said in Insert fill circle into cell of QTableWidget:

    You should also provide APIs that will allow you ton modify that matrix.
    As for the roles, they are there to retrieve specific information from the model's elements.

    I'm sorry but I still do not understand well the models and roles in QT.
    Can anyone give me an example of how the model class should be?

    I have a matrix (vector <vector <Cell >>) and when modifying some attributes of the Cell class, have to change what is painted in the graphic representation (Only the one in the cell corresponding to the coordinates of the matrix).


  • Lifetime Qt Champion

    @juaniyoalm
    Hi
    Its something like this
    https://meetingcpp.com/blog/items/an-introduction-into-qt-part-3.html
    However he uses a
    std::vector<PersonalData> mydata;
    where you have
    vector <vector <Cell >>
    so you need to use both index.row and index.col
    to address your matrix. ( the data)



  • @mrjj Thanks so much.

    I was doing it that way, but how did I assign the matrix to the model variable? At this moment, I am creating the matrix in mainwindow class ...


  • Lifetime Qt Champion

    @juaniyoalm
    Hi
    well the vector <vector <Cell >> matrix could be inside the model
    and you would use method like the Addperson in sample to fill it.
    Much like you do now. when maxtrix is outside of the model.
    You could also fill it in mainwindow and simply give whole matrix to model
    to copy it to internal variable.(matrix) but thats a bit waste full.

    Also i been wanting to ask you. You do use a TableView because you need scrolling correct?
    I mean there are far more rows with cells than can fit on on screen ?



  • @mrjj

    Yes, there is no row limit, it can be 20 rows, 100 or 1000 xD. I always have to think about what I do to behave well when I do the parallel implementation, using pthread and openmp.


  • Lifetime Qt Champion

    @juaniyoalm
    Ok so scrolling is needed:)
    Also make sure to check out QtConcurrent and QThread before jumping to pthread.



  • @mrjj

    ok, I will look it.

    I have a doubt, when I modify a value of the Cell class (this is done in a method of the Cell class ), it will be modified automatically in the model or I have to do model-> setData (model-> index (i, j) , matrix [i] [j] -> getModifiedValue ())? The Cell of matrix are pointer...


  • Lifetime Qt Champion

    @juaniyoalm
    Well if you go with QAbstractTableModel
    your matrix IS the data so if you modify it
    and call dataChanged (model call ) to let view know data has been altered.



  • @mrjj

    ok, this is my model implementation:

    /#include "cellmodel.h"
    
    CellModel::CellModel(QObject *parent) : QAbstractTableModel(parent){}
    CellModel::CellModel(int rows, int columns, int fungivores)
    {
        this->mundo = new World(rows, columns, fungivores);
    }
    
    int CellModel::rowCount(const QModelIndex &parent) const
    {
        return this->mundo->world.size();
    }
    int CellModel::columnCount(const QModelIndex &parent) const
    {
        return this->mundo->world[0].size();
    }
    
    QVariant CellModel::data(const QModelIndex &index, int role) const
    {
        if(!index.isValid())
            return QVariant();
    
        if(index.row() >= mundo->world.size() || index.row() < 0 ||
               index.column() >= mundo->world[0].size() || index.column() < 0)
            return QVariant();
    
        if(role == Qt::DisplayRole || role == Qt::EditRole)
        {
            return this->mundo->world[index.row()][index.column()]->getFood();
        }
        return QVariant();
    }
    
    bool CellModel::setData(const QModelIndex &index, const QVariant &value, int role)
    {
        if (index.isValid() && role == Qt::EditRole && !(index.row() >= this->mundo->world.size() || index.row() < 0 ||
                                                         index.column() >= this->mundo->world[0].size() || index.column() < 0))
        {
            int row = index.row();
            int col = index.column();
    
            this->mundo->world[row][col]->setFood(value.toInt());
    
            emit dataChanged(index, index);
            return true;
        }
        return false;
    }
    
    Qt::ItemFlags CellModel::flags(const QModelIndex &index) const
    {
        if (!index.isValid())
            return Qt::ItemIsEnabled;
        return QAbstractTableModel::flags(index) | Qt::ItemIsEditable;
    }
    
    
    

    if I modify the value in this way: model-> world-> world [0] [0] -> setFood (200);

    1- All row is changed instead of just the selected cell.

    2 - Repaint all matrix, although the data of the others have not changed.


  • Lifetime Qt Champion

    hi
    If you place break point and check
    CellModel::data
    return this->mundo->world[index.row()][index.column()]->getFood();
    is row and index what you expect and does getFood() return different values?

    it looks ok.
    very much like
    http://doc.qt.io/qt-5/qtwidgets-itemviews-addressbook-tablemodel-cpp.html


Log in to reply
 

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