有人可以帮我修改此代码吗?我正在尝试显示C++QT的棋盘格

can someone help me modify this code. I'm trying to Display a checkerboard C++ QT

本文关键字:显示 棋盘格 C++QT 修改 代码      更新时间:2023-10-16

我是Qt和C++的新手。我正在尝试创建一个棋盘/棋盘,其中每个方块都是一个对象。我想弄清楚的是,如何让每个方形对象成为我声明的板对象的一部分,并将其显示在屏幕上。我可以通过在主类中使用 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();
}

董事会和董事会.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);
}

您的Square被创建为自动变量(即,它的生存期是Board构造函数的范围(。 show()将使小部件可见,只要事件循环可以处理小部件,这里的情况并非如此(square将在事件循环之前被删除(。

此外,您应该在派生自 QObject 的每个类中添加 Q_OBJECT 宏。 Board派生自QWidget,而派生自QObject

因此,更改您的班级Board

class Square;
class Board : public QWidget
{
Q_OBJECT
public:
    Board();
private:
    Square* square;
};

构造函数:

Board::Board()
{
    square = new Square();
    square->show();
}

和析构函数:

Board::~ Board()
{
    delete square;
}

注意:对我来说,Square课是没有用的。您可以在Board paintEvent绘制网格,它会更快,消耗更少的内存,并且更易于维护。

编辑:这是一个更好的方法:

void Board::paintEvent(QPaintEvent* pe)
{
    // Initialization
    unsigned int numCellX = 8, numCellY = 8;
    QRect wRect = rect();
    unsigned int cellSizeX = wRect.width() / numCellX;
    unsigned int cellSizeY = wRect.height() / numCellY;
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    // Draw the background. The whole widget is drawed.
    painter.setBrush(QColor(0,0,0)); //black
    painter.drawRect(wRect);
    // Draw the cells which are of the other color
    // Note: the grid may not fit in the whole rect, because the size of the widget
    // should be a multiple of the size of the cells. If not, a black line at the right
    // and at the bottom may appear.
    painter.setBrush(QColor(255,255,255)); //white
    for(unsigned int j = 0; j < numCellY; j++)
        for(unsigned int i = j % 2; i < numCellX; i+=2)
            painter.drawRect(i * cellSizeX, j * cellSizeY, cellSizeX, cellSizeY);
}