[Qt-interest] A new (?) const-correct way to create a Ui object and do setupUi
Niels Dekker (Qt-interest)
mymailfromqt at xs4all.nl
Tue Feb 8 11:33:38 CET 2011
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.
Kind regards, Niels
--
Niels Dekker
http://www.xs4all.nl/~nd/dekkerware
Scientific programmer at LKEB, Leiden University Medical Center
More information about the Qt-interest-old
mailing list