Display a control panel with each square as an object - C ++ QT

I am new to Qt, but not too C ++. I am trying to create a chessboard where each square is an object. I am trying to figure out how each square object is part of the board object, which I declare and display on the screen. I can display the widget on the screen using MyWidget.show () in the main class. But I want to do something like Board.show () and show all the square objects that are members of this class (which have height, width and color). With the code I tried, nothing appeared, although I was able to get a square to show that it is 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 am noob with Qt, so most of what my code guessed and what I could find on google.

+4
source share
2 answers

There are several errors in the code:

  • You create a Square object on the stack. in the Board::Board() constructor. A square is created and deleted immediately when it exits the constructor. So create it on a heap.
  • A square requires a parent, so when you create a square, square = new Square(this);
  • Your board is basically a collection of squares, so create the QVector<Square*> squaresVec in the private members of the Council class. Now in the Board () constructor, create as many squares as you need and insert them into the QGridLayout (at the same time, save the pointers in the squaresVec variable for future purposes). Then use this->setLayout(gridLayout);
  • Also, your square widget has no size, so set the size (just use resize() )
+3
source
+3
source

Source: https://habr.com/ru/post/1368859/


All Articles