PDA

View Full Version : Stop multiple appearances of a widget in the same window



Akame.L
13th March 2017, 16:39
Hello,
I have a vertical layout (called center) & 3 buttons (aide,info,prom).
for each button clicked i want to add a specific widget into the vertical layout.
the problem is everytime a button is clicked it specific wigdet will apear if i click another botton or the same button again it will add another wigdet next to the previous one.
How can I stop that from happening.
Here what I have so far:


...
void employe::on_aide_clicked()
{
aide *a = new aide();
ui->center->addWidget(a,Qt::AlignLeft);
}
void employe::on_info_clicked()
{
empInfo *i = new empInfo();
ui->center->addWidget(i,Qt::AlignLeft);
}

void employe::on_prom_clicked()
{
demPro *d = new demPro();
ui->center->addWidget(d,Qt::AlignLeft);
}

d_stranz
14th March 2017, 03:54
Well, that's exactly what your code is telling it to do - each time you click any of the three buttons, it will add -another- instance of the same widget to the layout.

What do you really want to do? Add the widget once, the first time the button is clicked and never again? Destroy the old widget (if any) when the button is clicked and then add a new one? Or something else?

Write down (in words) what you want to happen, then try to write the code to do that. Report back here on youor results, but not before you try that.

Akame.L
14th March 2017, 10:14
For each button clicked I want to add one & only one widget. If another botton is clicked remove the previous one & add the new one to the layout.
The layout can have just one widget.
here what I tried:
I declared all the widgets in the header file


void employe::on_aide_clicked(){
if(!ui->center->isEmpty()){
ui->center->removeWidget(i);
ui->center->removeWidget(d);
}
ui->center->addWidget(a,Qt::AlignLeft);
}

& then did the same thing for the rest buttons
It works but since I'm a newbie I don't know if it's the right thing to do or if it's just a messy solution.

Ginsengelf
14th March 2017, 13:21
Hi, if you only want to display one of the three widgets at a time, maybe QStackedWidget is what you are looking for.

Ginsengelf

d_stranz
15th March 2017, 01:00
maybe QStackedWidget is what you are looking for.

Yes. Add the QStackedWidget to your vertical layout, then add the three sub-widgets as pages in the stack. Assign a stack page index (0, 1, or 2) to each of your buttons. So when the button for "a" is clicked, you set the current stack page to 0, for example. If you want a situation where -none- of the three sub-widgets is visible, then just add a plain QWidget instance as one of the pages.