我是 Qt 的新手,但不是 C++ 的新手。我正在尝试创建一个棋盘/棋盘,其中每个方 block 都是一个对象。我想弄清楚的是如何让每个方形对象成为我声明的板对象的一部分并将其显示在屏幕上。我可以在主类中使用 MyWidget.show() 在屏幕上显示小部件。但我想做一些类似 Board.show() 的事情,并显示属于该类(具有高度、宽度和颜色)的所有方形对象。使用代码我尝试没有任何显示,尽管我能够显示一个不在棋盘类中的正方形。
主要.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 和 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 和 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);
}
同样,我是 Qt 的菜鸟,所以我的大部分代码都是靠猜测工作的,我可以在谷歌上找到。
最佳答案
代码中的一些错误:
- 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()
)
关于c++ - 显示以每个方 block 为对象的棋盘 - C++ QT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7182315/