[Qt-interest] A new (?) const-correct way to create a Uiobjectand do setupUi
Niels Dekker (Qt-interest)
mymailfromqt at xs4all.nl
Tue Feb 8 17:43:06 CET 2011
>> During the lifetime of the form (e.g., CalculatorForm), its ui data
>> member
>> should never be NULL. So in my opinion, a reference to the Ui object is
>> more appropriate than a pointer.
Thiago Macieira wrote:
> Ok, that sounds fair.
>> [...] I stored the Ui object inside a little helper class,
>> derived from QObject. But that's an implementation detail of
>> CreateAndSetupUi(T&).
> So your implementation is even more complex and costly... More or less
> like this, right?
>
> template <typename T>
> class UiHolder: public QObject
> {
> public:
> T ui;
> UiHolder(QObject *parent) : QObject(parent) {}
> };
>
> template <typename T, typename BaseClass>
> const T &createAndSetupUi(BaseClass *parent)
> {
> UiHolder<T> *ptr = new UiHolder<T>(parent);
> ptr->ui.setupUi(parent);
> return ptr->ui;
> }
Right! Your UiHolder<T> class looks exactly like the one I implemented :-)
You createAndSetupUi basically does the same as my CreateAndSetupUi, except
for the fact that mine returns a proxy:
template <typename T_Parent>
UiProxy<T_Parent> CreateAndSetupUi(T_Parent& parent)
{
return UiProxy<T_Parent>(parent);
}
The proxy is there, just to simplify the syntax at the caller side. At the
caller side, I like to do:
CalculatorForm::CalculatorForm(QWidget *parent)
: QWidget(parent),
ui( CreateAndSetupUi(*this) )
{
}
Instead of having to specify the first template argument:
CalculatorForm::CalculatorForm(QWidget *parent)
: QWidget(parent),
ui( createAndSetupUi<Ui::CalculatorForm>(*this) )
{
}
The proxy, UiProxy<T_Parent>, converts implicitly to a const-reference to
the Ui object. (Internally it does new UiHolder<T>(parent) and
ptr->ui.setupUi(parent)).
But honestly, this proxy is just a nicety to me. I'd be happy to use your
createAndSetupUi, if it returns a const-reference to the created Ui object.
> This creates a QObject (8 or 16 bytes, plus overhead), a QObjectPrivate
> (80
> or 144 bytes, plus overhead) and adds it to the parent's list of children.
I have not done any profiling on this. Do you think the overhead of using an
extra QObject per Ui object may be experienced by the end-user?
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