[Solved] QList append every other object
-
I have a QList and when I attempt to append instances to it, it will only succeed every other attempt.
in mainwindow.h
@private:
QList<SimDevice*> deviceList;void addDevice(QString name);
@
in mainWindow.cpp
@
deviceList = QList<SimDevice*>(); //DeviceList();
@ and
@
void MainWindow::addDevice(QString deviceName){
deviceList.append(new SimDevice(deviceName));
}
@
The SimDevice class
@
class SimDevice
{
public:
SimDevice(QString name);
~SimDevice();
QString getDeviceName();
private:
QString deviceName;
};
@
And when I add elements and check on them
@
addDevice("bar");
addDevice("foo");
addDevice("junk");
addDevice("trash");
addDevice("stuff");
for (int i = 0; i < deviceList.count(); i++){
SimDevice *device = deviceList.takeAt(i);
QString name = device->getDeviceName();
qDebug() << name;
}
@
the result is
Starting /home/ray/Qt/projects/build-SimController-Desktop_Qt_5_3_GCC_64bit-Debug/SimController...
"bar"
"junk"
"stuff"
/home/ray/Qt/projects/build-SimController-Desktop_Qt_5_3_GCC_64bit-Debug/SimController exited with code 0 -
Here is a minimal example. What am I doing wrong?
@
MainWindow::MainWindow(QWidget parent)
: QMainWindow(parent)
{
deviceList = QList<SimDevice>(); //DeviceList();
addDevice("bar");
addDevice("foo");
addDevice("junk");
addDevice("trash");
addDevice("stuff");for (int i = 0; i < deviceList.count(); i++){ SimDevice *device = deviceList.takeAt(i); QString name = device->getDeviceName(); qDebug() << name; }
}
void MainWindow::addDevice(QString deviceName){
deviceList.append(new SimDevice(deviceName));
}@
@
class SimDevice
{
public:
SimDevice(QString name);
~SimDevice();
QString getDeviceName();
private:
QString deviceName;
};
@
@
SimDevice::SimDevice(QString name)
{
deviceName = name;
}QString SimDevice::getDeviceName(){
return deviceName;
}@Starting /home/ray/build-TestQList-Desktop_Qt_5_3_GCC_64bit-Debug/TestQList...
"bar"
"junk"
"stuff"
/home/ray/build-TestQList-Desktop_Qt_5_3_GCC_64bit-Debug/TestQList exited with code 0 -
Hi,
Use at() instead of takeAt(). takeAt() removes the item from your list, which shifts the positions of all the other items in your list.
P.S. Remember to delete your SimDevice objects when you don't need them anymore.
-
A note that is not related to your problem
You don't need this line in your MainWindow constructor
@
deviceList = QList<SimDevice*>(); //DeviceList();
@ -
JKSH: Thanks, I guess I should have RTFM. I just used takeAt in another area, I did need to remove the element, but I spaced on that fine point. Thank you
andreyc: Thanks for the tip.