> On 29 Oct 2025, at 01:42, Ville Voutilainen <[email protected]> 
> wrote:
> 
> On Tue, 28 Oct 2025 at 23:15, Volker Hilsheimer <[email protected]> 
> wrote:
>>> Precisely so. Our ostensible declaration (and definition) is
>>> 
>>> class QObject {
>>> ...
>>> public:
>>> template <class Child, class... Args>
>>> Child* makeChildObject(Args&&... args)
>>> {
>>>    return new Child(std::forward<Args>(args)..., this);
>>> }
>>> };
>>> 
>>> and that's all there is to it.
>>> 
>>> The reason it's a reach too far to return some
>>> semantically-parented-pointer instead is adoptability.
>>> With this approach, you can just change
>>> 
>>> MyType* var = new MyType(foo, bar, someParent);
>>> 
>>> to
>>> 
>>> MyType* var = someParent->makeChildObject<MyType>(foo, bar);
>>> 
>>> and there's no need for heavier refactorings in how that code uses
>>> MyType*. It doesn't need to be refactored to
>>> use a parented_ptr everywhere.
>> 
>> 
>> The above pattern seems to me to be the most pragmatic approach for an API 
>> addition to Qt. Perhaps also a QObject::addChild(std::unique_ptr<QObject *> 
>> child) which moves the ownership of the pointer held by child into the 
>> callee.
>> 
>> 
>> I do see that a parented_ptr<> type makes the intent clear to readers, 
>> static analysers, AI tools etc, in the same way that std::move’ing a 
>> std::unique_ptr would. And that type then producing clear failures (compile 
>> time if possible, although in practice it will have to be runtime 
>> assertions) in case of incorrect usage might be practical. But that can be 
>> achieved via explicit declaration of the variable, e.g.
>> 
>> parented_ptr<QLineEdit> input = dialog->makeChildWidget<QLineEdit>();
>> // would assert in ~parented_ptr if ‘input’ doesn’t have a parent
>> 
>> 
>> This makes the intent clear, while still allowing
>> 
>> QLineEdit *input = dialog->makeChildWidget<QLineEdit>();
> 
> Sounds like a plan. Would you do the honors of producing a patch for all that?
> 
> And QParentedPointer instead of parented_ptr, right? :)


If “you” is “Volker”, then not in the near future - but hopefully this 
conversation has given Daniel some input.

One thing to consider in this context is if/how we’d like QLayout to be part of 
this logic. When building a widget UI, QLayout is ultimately responsible for 
taking core of the correct parent/child relationships etc. Opinions vary on 
that topic, but I typically create child widgets without parent and rely on the 
layout. So, we might find out that a QLayout::makeChildWidget makes sense.

Volker


-- 
Development mailing list
[email protected]
https://lists.qt-project.org/listinfo/development

Reply via email to