我需要在Qt中使用512个单独的矩形项,我在QGraphicsScene中实现。除非我真的需要,否则我并不想手动声明所有512个元素。目前我有类似的东西:
QGraphicsRectItem *rec1;
QGraphicsRectItem *rec2;
QGraphicsRectItem *rec3;
QGraphicsRectItem *rec4;
QGraphicsRectItem *rec5;
QGraphicsRectItem *rec6;
QGraphicsRectItem *rec7;
QGraphicsRectItem *rec8;
QGraphicsRectItem *rec9;
QGraphicsRectItem *rec10;
QGraphicsRectItem *rec11;
QGraphicsRectItem *rec12;
等等。这必须达到rec512。
我试图实现一个for循环来为我做这个:
for(int i = 1;i=512;i++){
QGraphicsRectItem *rec[i];
}
然而,我收到一条错误,说“'期望的会员姓名或者;在声明说明符'
之后我认为这里不可能实现循环,有没有其他方法可以轻松声明所有512项?
谢谢:)
答案 0 :(得分:0)
感谢Benjamin Lindley指出明显使用数组,这完全让我不知所措。
QGraphicsRectItem *rec[512];
答案 1 :(得分:0)
更好的方法:
// in some .cpp file
#include <QVector>
#include <QSharedPointer>
#include <QDebug>
// Suppose we have some Test class with constructor, destructor and some methods
class Test
{
public:
Test()
{
qDebug() << "Creation";
}
~Test()
{
qDebug() << "Destruction";
}
void doStuff()
{
qDebug() << "Do stuff";
}
};
void example()
{
// create container with 4 empty shared poiters to Test objects
QVector< QSharedPointer<Test> > items(4);
// create shared poiters to Test objects
for ( int i = 0; i < items.size(); ++i )
{
items[i] = QSharedPointer<Test>(new Test());
}
// do some stuff with objects
for ( int i = 0; i < items.size(); ++i )
{
items.at(i)->doStuff();
}
// all Test objects will be automatically removed here (thanks to QSharedPointer)
}
在你的项目中,你应该用 QGraphicsRectItem (或其他一些类)替换 Test 并调用适当的函数。祝你好运!