簡體   English   中英

如何初始化QGraphicsItem的二維數組

[英]How to Initialize 2D Array of QGraphicsItem

我在一些gui東西上使用Qt,並且繼承了QGraphicsScene來實現自己的一些方法,我要做的一件事情是創建一個QGraphicsItems列表,特別是創建的一個2D數組,它繼承了QGraphicsItem 。

MatrixButton **buttons;

然后,當我從QGraphicsScene使用此方法初始化列表時,遇到了分段錯誤。

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

當我調試應用程序時,調試器告訴我問題是由QGraphicsItem.h中的以下行引起的:

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

具體來說,根據調試器,當ax = 640ay = 0 ,會發生故障。 我不了解在這種情況下會導致細分錯誤的原因。

您的問題是您使用x作為行的索引,使用y作為列的索引,但是邊界條件恰好相反

因此,將您的代碼修改為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM