Passing Widget to annother Widget
-
I want to create a QVector of different Widgets and give them to annother Widget class to manage them.
Is it possible?
Passing by const reference does not seem to work because copy is disabled.
Just to give an idea:
class Bar : public QWidget { //.... }; class Foo : public QWidget { Foo(const QVector<Bar *> &bars, QWidget *parent = nullptr) :QWidget{ parent }, mBars{bars} { } private: QVector<Bar *> mBars; };
-
Hi
QVector<Bar *> mBars;
should work. It must be a pointer.Note to show them, you will insert them into other widgets ?
Watch out for ownership issues as if you let any one but Foo class handle them/use them.
-
i found the issue in my real code i wrote
std::vector
instead ofQVector
in the constructor. That's why i wondered, that it was not working. -
@sandro4912
std::vector<Bar *> should also work but
& (refs ) will not.
Maybe that was the actual difference ? -
Yes i guess.
Isn't it that i have two options?
Foo(const QVector<Bar *> &bars, QWidget *parent = nullptr) :QWidget{ parent }, mBars{bars} { }
Foo(QVector<Bar *> bars, QWidget *parent = nullptr) :QWidget{ parent }, mBars{std::move(bars)} { }
And for the Understanding. I allocate the
Bar
Widgets on the heap withnew
. They have no parent then.When i pass them to
Foo
they get owned byFoo
when i add them to a layout right? -
@sandro4912 said in Passing Widget to annother Widget:
they get owned by Foo when i add them to a layout right?
Yes. When used with layouts, the layout/layouts parent will own the widget
so unless you use TakeAt on the layout to get it back, it will be deleted with parent and you have a dangling pointer in list.However, if you use them all in same place, it should be easy to handle.
-
I use the approach like this:
auto cells = createCells(width, height, countOfMines); randomizeCells(cells); auto newMinefield = new Minefield{ cells, width, height };
After this is run the local
Cells
is destroyed,I want to create the
Cells
independet from theMinefield
so i can run easier unit tests with handmadeCells
(not randomized) -
@sandro4912 said in Passing Widget to annother Widget:
I want to create the Cells independet from the Minefield
Maybe I don't see something, but what exactly is the problem?
What are these cells? -
Hi
auto newMinefield = new Minefield{ cells, width, height };Seems fine. Will MineField then delete the cells list or will
it leave it alone and somebody else will delete the cells?In any case, this should not be an issue if handled correctly.
-
Minefield puts the Cells into its layout.
Minefield later gets explicit delete with
delete Minefield
(and then gets replaced with a newMinefield
at runtime).The Cells are one field of the Minefield which is in the normal game each time generated with random content.
By having the Cells created outside I can create not random Cells for testing.
-
Hi
Well if the rule is that a cell list will be owned by the minefield
once given to it and will die with it i think it will work fine :)