PDA

View Full Version : How to iterate a QList of structs and modify struct elements directly?



bobbayribs
19th December 2017, 07:33
Hi, I'm trying to iterate through a QList of structs and modify elements within the struct, but can't figure it out.

My header looks like this:


struct buttonsStruct
{
QPushButton *pb;
QString s;
QWidget *w;
};

QPushButton *m_fireButton;
QPushButton *m_iceButton;


In my cpp file, create two struct objects and add them to a QList.


buttonsStruct b1 = {m_fireButton, "Fire", m_tabFire};
buttonsStruct b2 = {m_iceButton, "Ice", m_tabIce};

QList<buttonsStruct*> buttonsQList;
buttonsQList.append(&b1);
buttonsQList.append(&b2);


I iterate through out each QList struct, creating a new QPushButton.



QMutableListIterator<buttonsStruct*> it(buttonsQList);
while (it.hasNext())
{
buttonsStruct *bs = it.next();

bs->pb = new QPushButton(m_centralWidget);
(bs->pb)->setGeometry(QRect(xpos, ypos, 85, 25));
(bs->pb)->setText(bs->s);
...
}


When I try to access m_fireButton, I get a crash, and checking the memory address, I get 0x0.

Isn't bs->pb the same address as m_fireButton or m_iceButton? I'm modifying my struct elements directly in the iterator, no?

I looked through the documentation and found QMutableListIterator::QMutableListIterator(QList<T> & list)

so the QList is passed by reference. I can't see where I went wrong here. Any help?

Lesiok
19th December 2017, 09:20
1. I can't see where You put something in m_fireButton.
2. You create b1 and b2 on heap and then You save its addresses. You have to create this objects with new. Think why.

bobbayribs
22nd December 2017, 00:43
I put something in m_fireButton with line #6:


bs->pb = new QPushButton(m_centralWidget);

bs->pb is a pointer to m_fireButton.

At least I thought so, I think a copy is occurring somewhere instead of the pointer itself.

Lesiok
22nd December 2017, 07:09
I put something in m_fireButton with line #6:


bs->pb = new QPushButton(m_centralWidget);

bs->pb is a pointer to m_fireButton.

At least I thought so, I think a copy is occurring somewhere instead of the pointer itself.
1. After this line bs->pb is pointing to new QPushButton no to m_fireButton.
2. bs->pb is NOT a pointer to m_fireButton. It is a pointer to QPushButton with the same value as m_fireButton.

Sorry, these are the basics of C ++ - nothing to Qt.