Frage

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?

War es hilfreich?

Lösung

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?

Andere Tipps

I'd personally not use QTableWidget for this purpose, even though it can do the trick, it is a huge overhead. Especially considering that a "cell" can effectively be represented by a single pixel of a bitmap. You can use a bitmap pixmap for a "canvas" and then draw it scaled without smoothing to make the pixels "bigger". And best of all, you can use the bitmap directly as a bool value, and it will even be more efficient than using a bool member since it will use only a single bit to signify if a cell is dead or alive, which will also be the graphical representation of the table. 2 birds with one stone. Not to mention how much more cache friendly would this representation be than a bunch of heavy and fat QWidget based objects scattered around in memory.

Also, going through the entire table to get the living cell count sounds like an utter waste. You'd be better off tracking the count via tracking the changes. You can either alter a count variable or even keep a registry with living cells if needed.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top