有人可以帮我修改这段代码。我正在尝试显示棋盘格C ++ QT

时间:2013-04-05 08:26:28

标签: c++ qt

我是Qt和C ++的新手。我正在尝试创建一个棋盘/棋盘,每个方格都是一个对象。我想弄清楚的是如何让每个方形对象成为我声明并在屏幕上显示的板对象的一部分。我可以通过在主类中使用MyWidget.show()在屏幕上显示一个小部件。但我想做一些像Board.show()这样的东西,并且让所有方形对象成为该类的成员(具有高度,宽度和颜色)。有了代码,我尝试了什么都没有出现,虽然我能够得到一个正方形,而不是在董事会班级。

的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和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);
}

1 个答案:

答案 0 :(得分:2)

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

另外,你should add the Q_OBJECT macro in every class derived from QObjectBoard源自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课程是没用的。您可以在paintEvent Board中绘制网格,它会更快,消耗更少的内存,并且更易于维护。

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

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