Is this good programming practice? And how do I declare only one instance?
Hey guys,
I am trying to have a common widget which is going to appear on several pages of a stackedwidget. In my example below, I did not connect the pushButtons but assume that pushButton1 will ask mStacked to show the first widget while pushButton2 will ask mStacked to show the second widget.
I've been declaring a few widgets as follows:
Note: Not complete code, but you get the idea.
Code:
{
mStacked->addWidget( commonWidget() ); //Declaration of Page 1
mStacked->addWidget( commonWidget() ); //Declaration of Page 2
mainLayout->addWidget(mStacked);
mainLayout->addWidget(pushButton1);
mainLayout->addWidget(pushButton2);
setLayout(mainLayout);
}
{
layout->addWidget(mLabel);
mWidget->setLayout(layout);
return mWidget;
}
I have two main questions:
1. Is this a good way of declaring a commonWidget?
2. If it's the usual way, is there a way to ensure that only one instance of mLabel is created? In otherwords, when I change the value of mLabel on one page, the same value is displayed on the other pages.
Thanks much.
Regards,
Pembar
Re: Is this good programming practice? And how do I declare only one instance?
Quote:
Originally Posted by
Pembar
1. Is this a good way of declaring a commonWidget?
It's fine although you could make the method const so that you can call it on constant objects and from other constant methods.
Quote:
2. If it's the usual way, is there a way to ensure that only one instance of mLabel is created?
No, if you want to show the widget on multiple pages, you have to have multiple copies of it. You can cheat by pointing several buttons to the same page so that you can use a single widget but only if it makes sense in your case.
Quote:
In otherwords, when I change the value of mLabel on one page, the same value is displayed on the other pages.
You can use signals and slots for that.
Re: Is this good programming practice? And how do I declare only one instance?
Quote:
Originally Posted by
wysota
Quote:
In otherwords, when I change the value of mLabel on one page, the same value is displayed on the other pages.
You can use signals and slots for that.
And then how would you like to get a pointer to the label? I know it's possible, but for that, to subclass QWidget regularly and provide public functions could be easier.
Re: Is this good programming practice? And how do I declare only one instance?
Got it, Thanks
Edit:
Just to give an idea on how I solved it. Each time I declared a new *mLabel, I pushed it into a List of pointers.
I then connected my "Change" pushbutton to go through all the Labels and changed every single one of them.
Regards,
Pembar
Re: Is this good programming practice? And how do I declare only one instance?
Quote:
Originally Posted by
Lykurg
And then how would you like to get a pointer to the label?
You have a pointer available when you are creating the widget. So its enough to setup the connections right after you have setup all the pages.