[Qt-interest] A new (?) const-correct way to create aUiobjectand do setupUi
Niels Dekker (Qt-interest)
mymailfromqt at xs4all.nl
Wed Feb 9 08:13:13 CET 2011
>> I wouldn't mind if a function like createAndSetupUi would return a
>> non-const reference. Leaving it up to the user whether the ui member
>> variable is a const, or a non-const reference.
Robert Hairgrove wrote:
> But I thought that the whole motivation for this project was to provide
> a const UI object? We already have the non-const version...
The motivation is to *allow* the user to declare the ui member as a
const reference, with only a *minimum* amount of boilerplate code. In
that sense, I think my CreateAndSetupUi function does the job:
In the header file of the user's form:
1. Forward-declare the Ui class.
2. Declare the ui member as a const reference
And in the cpp file of the user's form:
1. Include (#include) the definitions of CreateAndSetupUi and the Ui
class.
2. Initialize the ui member by CreateAndSetupUi(*this).
That's it. And FWIW, I think it's also more convenient to write e.g.,
"ui.pushButton" than "ui->pushButton".
> besides, I have yet to see the real benefit of having the
> UI member const. Who should change it? Either it is a private
> subclass or a private member variable (pointer or not).
I'm following Scott Meyers' recommendation to use const whenever
possible (Effective C++ Third Edition, item 3). Even for private data.
But of course, you are free to do otherwise.
However, I think a function like CreateAndSetupUi should not stop people
from doing retranslateUi at any time (if necessary). Do I understand
correctly that the call retranslateUi might as well be applied to a
*copy* of the ui, while still having the same effect? For a ui of type
UiClass, isn't ui.retranslateUi(this) equivalent to
UiClass(ui).retranslateUi(this)?
Of course, a helper function (template) might be more convenient:
template <class UiClass, class Parent>
void RetranslateUi(UiClass uiParam, Parent& parent)
{
uiParam.retranslateUi(&parent);
}
Allowing to do a retranslation of this->ui by RetranslateUi(ui, *this),
even when ui is a const reference. Right?
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