PDA

View Full Version : Trick for a non destructive QMainWindow::setCentralWidget ?



jwintz
7th March 2007, 00:00
Hello,

I would very much like my application to have a more or less "dynamic" central widget, at least I wanna be able to switch from a widget, say w1, to another, say w2, without loosing them each time I switch. The problem is QMainWindow::setCentralWidget(QWidget *) deletes the current QMainWindow::centralWidget().

Here is completely useless code which illustrates the idea.



class MainWindow : public QMainWindow
{
...
public slots:
void switchToW1(void) ;
void switchToW2(void) ;

private:
QWidget * w1 ;
QWidget * w2 ;
} ;

void MainWindow::switchToW1(void)
{
setCentralWidget(w1) ; // PROBLEM: deletes w2
}

void MainWindow::switchToW2(void)
{
setCentralWidget(w2) ; // PROBLEM: deletes w1
}


I've tried to avoid using setCentralWidget by using a QScrollArea but its QScrollArea::setWidget() method behaves the same way, i.e. it deletes the current widget.

Of course I end up trying stupid thing like (note this is pseudo code, so of course it does not work syntactically):



QWidget * dummy ;
QWidget * w1 = new ... ;
QWidget * w2 = new ... ;

setCentralWidget(dummy) ;

void MainWindow::switchToW1(void)
{
dummy = w1 ;
update() ;
}

void MainWindow::switchToW2(void)
{
dummy = w2 ;
update() ;
}


But, with no surprise, it does not work either.

Do anyone has a trick to do something like that correctly ?

Thanks. Ju.

jacek
7th March 2007, 00:06
How about using QStackedWidget as the central widget?

jwintz
7th March 2007, 00:22
I can't figure why I have a persistent horrible picture in mind of QStackWidget with two horrible arrows at its top left corner that systematically prevents me to consider using it. Terrible confusion.

Of course, you are right. Thank you.

fullmetalcoder
7th March 2007, 10:01
I can't figure why I have a persistent horrible picture in mind of QStackWidget with two horrible arrows at its top left corner that systematically prevents me to consider using it. Terrible confusion.
Maybe because it's the way it appears in Qt Designer so as to make it easy to navigate through pages... ;) I used to have the same confusion but I tried it in a dialogs and it appeared to be SO nice (and so easy to connect with QComboBox) that I kept it and started to use in many spots where I previously relied on dirty uglt hacks...:rolleyes:

jwintz
7th March 2007, 10:45
That's it ;-) And yes, it is really useful.