Important: Please read the Qt Code of Conduct -

Drawing colored grid with clickable cells

  • Hi there,
    I don't know if I solve this problem correctly and efficiently. I have to draw grid of elements, with row and column counts provided by user. After drawing it, I want user to be able to click the cells to select them (selected items are marked with different color). I've got spin inputs for rows and columns, push button to start drawing. I extend QWidget class as follows:

    class Box : public QWidget
        Box(QWidget *parent = nullptr) = delete;
        explicit Box(Cell *cell, QWidget *parent = nullptr);
        bool event(QEvent *event);
        Cell *cell;
    Box::Box(Cell *c, QWidget *parent) : cell(c), QWidget(parent) {}
    bool Box::event(QEvent *event)
        if (event->type() == QEvent::MouseButtonRelease)
            cell->setState((cell->getState() + 1) % 2); //changing state, not important here
            QPalette palette;
            palette.setColor(QPalette::Background, cell->getColor());
            return true;
        return QWidget::event(event);

    (Cell is class storing the state on which the color is based)
    On button clicked, I create as many Box objects as user requested and add them to grid layout defined in .ui file.
    It works perfectly, but I wonder if there is some simpler or more efficient way to achieve such grid with accessible (and clickable) items.
    Also, I have problem with keeping this grid layout fixed to window width (as its height is based on row number provided by user), but I think that this is problem for another topic.

  • Lifetime Qt Champion

    @kpusmo Maybe matches your requirements?

  • @jsulm thank you for your response. I achieved this using QTableView and model, that's much faster for large amount of cells than using QWidgets and grid layout. Also, it was easy to make QTableView expand on window resize.

Log in to reply