简体   繁体   中英

How to Initialize 2D Array of QGraphicsItem

I'm using Qt for some gui stuff, and I have inherited QGraphicsScene to implement some of my own methods, and one of the things I did was create a list of QGraphicsItems, specifically a 2D array of an object I made which inhertits the QGraphicsItem.

MatrixButton **buttons;

Then, when I initialize the list in this method from the QGraphicsScene, I get a segmentation fault.

void MatrixScene::initScene()
{
    this->setSceneRect(0, 0, this->width*BUTTON_SIZE, this->height*BUTTON_SIZE);
    this->currentFrameIndex = 0;
    this->color = Qt::red;
    this->buttons = new MatrixButton*[this->height];
    for (int i = 0; i < this->height; i++){
        this->buttons[i] = new MatrixButton[this->width];
    }
    for (int x = 0; x < this->width; x++){
        for (int y = 0; y < this->height; y++){
            this->buttons[x][y].setPos(x*BUTTON_SIZE, y*BUTTON_SIZE); //SEGMENTATION FAULT!!!
            this->addItem(&this->buttons[x][y]);
        }
    }
    this->update();
}

When I debug the application, the debugger tells me that the problem is caused by the following line in QGraphicsItem.h:

inline void QGraphicsItem::setPos(qreal ax, qreal ay)
{ setPos(QPointF(ax, ay)); }

Specifically, the fault occurs when ax = 640 and ay = 0 , according to the debugger. I don't understand what would be causing the segmentation fault in this case.

Your problem is you are using x as index for row and y as index for column but the boundary conditions are just opposite

So modify your code to :

for (int x = 0; x < this->height; x++){
        for (int y = 0; y < this->width; y++){
            this->buttons[x][y].setPos(x*BUTTON_SIZE, y*BUTTON_SIZE);        
            this->addItem(&this->buttons[x][y]);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM