lukassz - 14 days ago 5
C++ Question

# QT how to save to file QPoint 2d array

I have board where I can "draw" a number.

This is code of board

``````void PrintRectangle::paintEvent(QPaintEvent *)
{
for(int i=0; i<5; i++)
{
ypos=20;
for(int j=0; j<5; j++)
{
QColor color = Qt::white;
for(int k=0; k<points.size(); k++){

if( i == points[k].x() && j == points[k].y() )
{
color = Qt::black;
}

}
p.fillRect(xpos,ypos,recWidth,recHeight,color);
ypos+=60;
}
xpos+=60;
}
}
``````

And next function, which updated points on list

`````` QVector<QPoint> points;
void PrintRectangle::updateIndexFromPoint(const QPoint &point)
{
int x = point.x() - 20;
int y = point.y() - 20;
bool removed = false;

if( ( (x >= 0 )  && ( x <= 300) ) && ( (y >= 0 )  && ( y <= 300) ) )
{
mXIndex = x / 60; //rec width + spacing
mYIndex = y / 60; //rec height + spacing

for(int k=0; k<points.size(); k++){

qDebug("%d %d", points[k].x(), points[k].y());

if(points[k].x() == mXIndex && points[k].y() == mYIndex){

points.remove(k);
removed = true;
}

}

if(!removed){
points.append(QPoint(mXIndex,mYIndex));
}
}
}
``````

My question is how can I save to file numer from QPoint selected rectangle.

eg. numer 1 in file

``````0 0 1 0 0
0 1 1 0 0
1 0 1 0 0
0 0 1 0 0
0 0 1 0 0
``````

Simply use QDataStream to store your points in file:

``````void savePoints(QVector<QPoint> points)
{
QFile file("points.bin");
if(file.open(QIODevice::WriteOnly))
{
QDataStream out(&file);
out.setVersion(QDataStream::Qt_4_0);
out << points;
file.close();
}
}

{
QVector<QPoint> points;
QFile file("points.bin");
{
QDataStream in(&file);
in.setVersion(QDataStream::Qt_4_0);
in >> points;
file.close();
}
return points;
}
``````
Source (Stackoverflow)