Insert fill circle into cell of QTableWidget

  • @mrjj

    I can not return a cell in the data method of the model because it gives me an error:


  • Lifetime Qt Champion

    you try to return a Cell pointer.
    Should be like
    mundo->getCell(index.row(), index.column())->somePublicVariable
    mundo->getCell(index.row(), index.column())->Func(); // return some data, int , float , etc

    Why you want to return the cell pointer ?
    Just return some of its data

  • @mrjj

    I think I'm not understanding ... hah.

    If I put the following:


    When I modify the value in this method:


    Or these:


    That signals activate this method (slot):


    But in no time I pass the role and then the model does not know what data to return...

  • Lifetime Qt Champion

    The view itself ask for
    Qt::DisplayRole and Qt::EditRole ( if u edit cell )
    the new roles was for the delegate to request data it needs.

    You did study for more than a few minutes the
    right ?

  • @mrjj

    Ok, I understand now. The problems are solved:

    QVariant CellModel::data(const QModelIndex &index, int role) const
            return QVariant();
        if(index.row() >= mundo->getWorld().size() || index.row() < 0 ||
               index.column() >= mundo->getWorld()[0].size() || index.column() < 0)
            return QVariant();
        if(role == CircleSize)
            return this->mundo->getCell(index.row(), index.column())->getFungivoresSize();
        if(role == FoodCount)
            return this->mundo->getCell(index.row(), index.column())->getFood();
        return QVariant();

    And paint method:

    void CellDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
        int cellValue = index.model()->data(index, Qt::UserRole+2).toInt();
        qreal circleValue = index.model()->data(index, Qt::UserRole+1).toInt();
        qreal circleRealValue = (circleValue*20)/50;
        painter->fillRect(option.rect, QBrush(QColor((255 - cellValue), 255, 51)));
        painter->drawEllipse(static_cast<QPointF>(, circleRealValue, circleRealValue);
        painter->setRenderHint(QPainter::Antialiasing, true);

  • Lifetime Qt Champion

    Note you should try to reuse the CircleSize, FoodCount constexpr if possible
    instead of Qt::UserRole+1.
    you can just make a .h file and put them there and let both
    model and delegate include it.

  • @mrjj

    Ok I have already done it.

    I want to thank all of you who have tried to help me, especially @mrjj and @SGaist . You have had a lot of patience with me. Thank you.

    Surely I will have more questions about the project later. I'll stay here.

  • Lifetime Qt Champion

    Well good work then. :)
    Please mark as solved.
    You can always make new posts
    for new problems.

    and happy programming.

Log in to reply

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