Search code examples
c++qtqtablewidgetqtguiqtablewidgetitem

Qt - counting colored cells


I'm new in Qt, and I'm trying to implement Conway's game of life with a counter of "living cells" - the cell is alive when it's colored. I'm wondering how can I count the amount of colored cells in QTableWidget. I mean I can not do it using "if loop", because the compiler cannot convert QTableWidgetItem::backroundColor to bool variable. How can I do it?


Solution

  • the compiler cannot convert QTableWidgetItem::backroundColor to bool variable.

    First of all, there is no such a member of the class.

    Furthermore, you have not shown the concrete data type of backgroundColor, so I will assume it is QColor rather than a QString instead, et al.

    In that case, for instance these two QColor methods would aid your job:

    QColor::QColor(Qt::GlobalColor color)

    This is an overloaded function.

    Constructs a new color with a color value of color.

    and the following operator:

    bool QColor::operator==(const QColor & color) const

    Returns true if this color has the same RGB and alpha values as color; otherwise returns false.

    So, you could write something like this:

    const QColor redColor = QColor(Qt::red); // constant, initialized once
    

    and then you would the comparison like this:

    QBrush tableWidgetItemBrush = tableWidgetItem->background();
    if (tableWidgetItemBrush.color() == redColor)
        ++livingCells;
    

    Having provided the code for what you wish, I would suggest to reconsider this design in the future.

    I would use a different "core" representation with UI so that it is properly decoupled, and could be even stored in database directly, or reused in a command line based mud game, et al.

    Also, what if another day, you decide not make the difference based on color, but different patterns?