Q3DScatter Example promotes bad practice
-
I wasn't sure how to phrase this questions (and it is my first post here), but I was working with Qt's Q3DScatter example and there is a portion where they create a raw pointer to iterate (and modify elements) through a perfectly good vector (QScatterDataArray inherits from std::vector). This seems like bad practice and something a crazy gray beard would do because he thinks he knows better.
https://doc.qt.io/qt-5.10/qtdatavisualization-scatter-example.html
QScatterDataArray *dataArray = new QScatterDataArray; dataArray->resize(m_itemCount); QScatterDataItem *ptrToDataArray = &dataArray->first(); float limit = qSqrt(m_itemCount) / 2.0f; for (float i = -limit; i < limit; i++) { for (float j = -limit; j < limit; j++) { ptrToDataArray->setPosition(QVector3D(i + 0.5f, qCos(qDegreesToRadians((i * j) / m_curveDivider)), j + 0.5f)); ptrToDataArray++; } }
This makes way more sense; however, it blows up:
_dataArray->push_back(QScatterDataItem(QVector3D(0,0,0)));
I assume this has to do with ownership of the array to the data proxy, but there has to be a better way.
Mitch
-
Is this a general comment or do you have a specific question? I couldn't tell.
If it's a general comment, then yes, you're correct, it's a bad practice and the API seems to be rather bad. Why would anyone want to create and marshalQScatterDataArray
(a.k.a.QVector<QScatterDataItem>
) through the heap is quite beyond my comprehension. And yes, just using an iterator should've done the job fine, no need to take the "give me your first element's address, so I can loop around the array with a pointer" approach, even though it's correct, formally speaking. -
kshegunov,
Thanks for your response. You are correct I was not very clear about my question.Is there a better way to add elements to the "dataArray"?
Like I said if you use push_back it will blow up. I get the following error:
ASSERT: "!isEmpty()" in file /Users/Mitch/Qt/5.9.1/clang_64/lib/QtCore.framework/Headers/qvector.h, line 235In my specific case I have a vector of points I want to put in the "dataArray"; however, not all of the items are going to be added. If I was to use the method that Qt uses in their example, I would need to iterate through my vector counting how many elements need to be added, resize, and then iterate though my vector again in order to add the elements. That is why using push_back would be much easier.
Mitch
-
@Mitch9192 said in Q3DScatter Example promotes bad practice:
Is there a better way to add elements to the "dataArray"?
Indeed, QVector::append should do the job.
ASSERT: "!isEmpty()" in file /Users/Mitch/Qt/5.9.1/clang_64/lib/QtCore.framework/Headers/qvector.h, line 235
I imagine this is tripped in
QVector::first
because the vector's empty. I suggest using an iterator to loop over the data instead (refer to theQVector
documentation).