PDA

View Full Version : How do I create a 2 dimensional array of QGraphicsRectItems?



Guillermo-Gatoto
11th August 2017, 05:01
I need to display a dynamic amount of QGraphicsRectItems in a QGraphicsView in rows and columns, so I decided to create a 2D array, but I always get an error. This is my header:



#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QGraphicsRectItem>
#include <QMainWindow>
#include <QGraphicsScene>

namespace Ui{
class MainWindow;
}

class MainWindow : public QMainWindow{
Q_OBJECT

public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();

private:
Ui::MainWindow *ui;
QGraphicsRectItem*** objRect; //This would be my 2D array
};

#endif // MAINWINDOW_H




This is how I instance it:




objRect = new QGraphicsRectItem**[x];
for(int i = 0; i < x; i++){
objRect[i] = new QGraphicsRectItem*[x];
}



The code above runs perfectly with no errors. But whenever I try to do something with it, like establishing the size of one of the rectangles, it throws me an error message:



objRect[0][0]->setRect(0,0,100,100);



If I run the program normally, no error message appears, but the window doesn't even appear. I can only see the error message if I run the project in Debug mode.

This is the error message:

12543

"The inferior stopped because it received a message from the operating system"

Signal name: SIGSEGV

Signal meaning: Segmentation fault

I've tried a lot of different ways of instancing it, but nothing seems to work.

Ginsengelf
11th August 2017, 07:06
Hi, think it would be easier to use a standard container like QVector or QList instead of creating the array by yourself.

Ginsengelf

Santosh Reddy
11th August 2017, 11:13
So far good, but where are you allocating the object, that is only thing missing.

Here is a generic example


template <typename T>
T *** New2DArray(int rows, int cols)
{
T *** array = new T**[rows];

for(int r = 0; r < rows; ++r)
{
array[r] = new T*[cols];

for(int c = 0; c < cols; ++c)
array[r][c] = new T;
}

return array;
}

template <typename T>
void Delete2DArray(T *** array, int rows, int cols)
{
for(int r = 0; r < rows; ++r)
{
for(int c = 0; c < cols; ++c)
delete array[r][c];

delete[] array[r];
}

delete[] array;
}

...
QGraphicsRectItem *** objRect = New2DArray<QGraphicsRectItem>(rows, cols);
...
Delete2DArray(array, rows, cols);
...