gsgx
gsgx

Reputation: 12249

Displaying a checker board with each square as an object - C++ QT

I'm new to Qt but not too C++. I'm trying to create a checker/chess board where each square is an object. What I'm trying to figure out is how to have each square object be a part of the board object I'm declaring and display that on the screen. I can display a widget on the screen by using MyWidget.show() in the main class. But I want to do something like Board.show() and have all of the square objects that are members of that class(that have a height, width, and color) show up. With the code I tried nothing showed up, although I was able to get a square to show up that was NOT in the board class.

main.cpp

#include <qtgui>
#include "square.h"
#include "board.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    //Square square;
    //square.show();
    Board board;
    board.show();
    return app.exec();
}

board.h and board.cpp

#ifndef BOARD_H
#define BOARD_H

#include <QWidget>

class Board : public QWidget
{
public:
    Board();
};

#endif // BOARD_H

#include "board.h"
#include "square.h"

Board::Board()
{
    Square square;
    //square.show();
}

square.h and square.cpp

#ifndef SQUARE_H
#define SQUARE_H

#include <QWidget>

class Square : public QWidget
{
public:
    Square();

protected:
    void paintEvent(QPaintEvent *);
};

#endif // SQUARE_H

#include "square.h"
#include <QtGui>

Square::Square()
{
    QPalette palette(Square::palette());
    palette.setColor(backgroundRole(), Qt::white);
    setPalette(palette);
}

void Square::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(QBrush("#c56c00"));
    painter.drawRect(10, 15, 90, 60);
}

Again, I'm a noob with Qt, so most of what my code was guess work and what I could find on google.

Upvotes: 4

Views: 5617

Answers (2)

Chenna V
Chenna V

Reputation: 10523

A few things going wrong in the code:

  1. You are creating the Square object on the stack. in the Board::Board() constructor. The square is created and deleted right away when it gets out of the constructor. So create it on the heap.
  2. The Square needs a parent so when you create a square do
    square = new Square(this);
  3. Your board is basically a collection of squares so create a variable QVector<Square*> squaresVec in the private members of Board class. Now in the Board() constructor create as many squares as required and insert them into a QGridLayout (at the same time save the pointers in the squaresVec variable for future purposes). Then use this->setLayout(gridLayout);
  4. Also, your square widget doesn't have a size so set a size (simply use resize())

Upvotes: 3

TheHorse
TheHorse

Reputation: 2797

  1. use QGridLayout for Board
  2. set fixed size for each square (and may be size policy).
  3. set board as parent of each square (Square square(this);).

Upvotes: 3

Related Questions