1

我是 Qt 和 C++ 的新手。我正在尝试创建一个棋盘,其中每个方块都是一个对象。我想弄清楚的是如何让每个方形对象成为我要声明的板对象的一部分并将其显示在屏幕上。我可以在主类中使用 MyWidget.show() 在屏幕上显示一个小部件。但我想做类似 Board.show() 的事情,并让所有属于该类成员的方形对象(具有高度、宽度和颜色)显示出来。使用该代码,我尝试了没有任何显示,尽管我能够显示一个不在棋盘类中的方块。

主文件

#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);
}
4

1 回答 1

2

YourSquare被创建为一个自动变量(即,它的生命周期是 的构造函数的范围Board)。 show()只要事件循环可以处理小部件,就会使小部件可见,这里不是这种情况(square将在事件循环之前删除)。

此外,您应该Q_OBJECT在从QObject. 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上课是没用的。您可以在 中绘制一个网格paintEventBoard它会更快,消耗更少的内存,并且更易于维护。

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

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);
}
于 2013-04-05T08:39:47.767 回答