[Qt-interest] A new (?) const-correct way to create a Ui object and do setupUi
Robert Hairgrove
evorgriahr at hispeed.ch
Tue Feb 8 11:50:03 CET 2011
On Tue, 2011-02-08 at 11:33 +0100, Niels Dekker (Qt-interest) wrote:
> There are various ways to use the Ui class generated by the User Interface
> Compiler (uic), as described at
> http://doc.qt.nokia.com/4.7-snapshot/designer-using-a-ui-file.html
> Personally, I find the approach that has a Ui object as member variable the
> most intuitive one:
>
> #include "ui_calculatorform.h"
>
> class CalculatorForm : public QWidget
> {
> ...
> Ui::CalculatorForm ui;
> };
>
> However, this approach causes extra header file dependencies. So
> doc.qt.nokia.com also presents an alternative, removing the #include
> "ui_calculatorform.h" from the header file, and declaring the Ui member
> variable as a pointer. I certainly find this an interesting alternative. But
> instead of a pointer, I'd rather have a reference. Or even better: a const
> reference! Protecting the Ui object against any accidental modifications! It
> took me some time to figure out a convenient way to support declaring the Ui
> member variable as a const reference. But I think I got it working now, by
> introducing a template function, CreateAndSetupUi(T&). To be used as
> follows:
>
> class CalculatorForm : public QWidget
> {
> ...
> const Ui::CalculatorForm& ui;
> };
>
> CalculatorForm::CalculatorForm(QWidget *parent)
> : QWidget(parent),
> ui( CreateAndSetupUi(*this) )
> {
> }
>
> Note that the ui reference does not need to be deleted. (It cannot even be
> deleted, of course, because it is not a pointer!) The argument of
> CreateAndSetupUi(T&) is used as parent of the newly created Ui object, so it
> will take care of deallocation. Internally, the argument is also passed to
> setupUi.
>
> Actually the template function does not really return a reference to the
> created Ui object. It returns a proxy object, which converts implicitly to a
> (const) reference of the right Ui class type.
>
> Is this idea of interest to anyone else here? I wouldn't mind sharing the
> implementation of CreateAndSetupUi. But I'm also interested to hear if such
> an approach is already presented elsewhere.
If "ui" is const, you cannot call any of the non-const functions on any
of the GUI objects it contains ... such as setText() on an edit control,
for example. I think this would be severely limiting.
As to deletion, normally the parent of an object which inherits QObject
will delete its children automatically. I would think that creating ui
as a member object variable would lead to a double deletion, but I might
be mistaken.
More information about the Qt-interest-old
mailing list