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:
开发者_StackOverflow中文版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.
A few things going wrong in the code:
- 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.- The Square needs a parent so when you create a square do
square = new Square(this);
- 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 thesquaresVec
variable for future purposes). Then usethis->setLayout(gridLayout);
- Also, your square widget doesn't have a size so set a size (simply use
resize()
)
- use QGridLayout for Board
- set fixed size for each square (and may be size policy).
- set board as parent of each square (
Square square(this);
).
精彩评论