c++ - 显示以每个方 block 为对象的棋盘 - C++ QT

标签 c++ qt

我是 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 的菜鸟,所以我的大部分代码都是靠猜测工作的,我可以在谷歌上找到。

最佳答案

代码中的一些错误:

  1. 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.
  2. The Square needs a parent so when you create a square do
    square = new Square(this);
  3. 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 the squaresVec variable for future purposes). Then use this->setLayout(gridLayout);
  4. 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/

相关文章:

c++ - glDrawElements 不渲染任何东西

c++ - 命名 union 的原因是什么?

Qt:在 QScrollArea 中的小部件上调用 setGeometry 时出现奇怪的行为

visual-studio-2010 - 无法在发行版中构建 qt5

linux - QT下打开已有的sqlite3数据库

c++ - 关闭qt应用程序时,想杀死qprocess

c++ - qt/c++ 应用程序中的实时问题

c# - 键盘操作

python - 停止嵌入式 python

C++空间问题