After some research, I found a "partial" solution to the problem.
If you create a layout and control widgets with it, you can get this layout later in the code using the dynamic properties of Qt. Now, in order to use QWidget :: setProperty (), the object you are about to store must be a registered meta type. A pointer to a QHBoxLayout is not a registered meta type, but there are two workarounds. The simplest workaround is to register the object by adding this anywhere in your code:
Q_DECLARE_METATYPE(QHBoxLayout*)
The second workaround is to wrap the object:
struct Layout { QHBoxLayout* layout; }; Q_DECLARE_METATYPE(Layout)
Once an object is a registered meta-type, you can save it as follows:
QHBoxLayout* layout = new QHBoxLayout; QWidget* widget = new QWidget; widget->setProperty("managingLayout", QVariant::fromValue(layout)); layout->addWidget(widget);
Or, if you used the second workaround:
QHBoxLayout* layout = new QHBoxLayout; QWidget* widget = new QWidget; Layout l; l.layout = layout; widget->setProperty("managingLayout", QVariant::fromValue(l)); layout->addWidget(widget);
Later, when you need to get the layout, you can get it as follows:
QHBoxLayout* layout = widget->property("managingLayout").value<QHBoxLayout*>();
Or like this:
Layout l = widget->property("managingLayout").value<Layout>(); QHBoxLayout* layout = l.layout;
This approach is applicable only when creating a layout. If you have not created the layout and installed it, then there is no easy way to get it later. You will also need to track the layout and update the manageLayout property when necessary.
Austin
source share