繁体   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