PDA

View Full Version : "Change widget class on button click" problem



utkozanenje
22nd May 2011, 17:24
Hi, I'm making qt gui application, and in mainwindow I have QWidget, which should become one of my custom widgets..

here's a code


MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
QWidget *tempWidget = new QWidget(this);
setMinimumSize(800,600);
QFormLayout *mainLayout=new QFormLayout();
QVBoxLayout *btnsLayout=new QVBoxLayout;
btns=new QGroupBox;
widget=new QWidget;
widget->setStyleSheet("height: 400px; width: 500px;");
onlineGameButton=new QPushButton("ONLINE GAME");
connect(onlineGameButton, SIGNAL(clicked()), this, SLOT(newOnlineGame()));
offlineGameButton=new QPushButton("OFFLINE GAME");
simulateGameButton=new QPushButton("SIMULATE GAME");
optionsButton=new QPushButton("OPTIONS");
exitButton=new QPushButton("EXIT");
connect(exitButton, SIGNAL(clicked()), this, SLOT(exitProgram()));
btnsLayout->addWidget(onlineGameButton);
btnsLayout->addWidget(offlineGameButton);
btnsLayout->addWidget(simulateGameButton);
btnsLayout->addWidget(optionsButton);
btnsLayout->addWidget(exitButton);
btnsLayout->addStretch();
btns->setLayout(btnsLayout);
mainLayout->addRow(btns, widget);
...
tempWidget->setLayout(mainLayout);
setCentralWidget(tempWidget);
}


void MainWindow::newOnlineGame()
{
widget=new GameWidgetView;
}

i used debug to view if event is fired, and it is, but nothing happend, widget didn't become GameWidgetView...

widget is defined as private member of MainWindow, so when I add it to centralwidget, when i change widget, it should be changed and "that widget" in centralwidget, too, right(because of reference)?

sorry for my english

wysota
22nd May 2011, 17:43
You only create a new widget and assign it to some variable. There is no "replacement" going on. If you want to replace one widget with another then either use QStackedWidget or delete the old widget and place the new one in a layout where the old widget was.

utkozanenje
22nd May 2011, 18:05
great! thanks lot, it works.

these are correction
//first change stupid name widget to less stupid name _widget :)
in mainwindow.h

QStackedWidget *_widget;

in mainwindow.cpp

_widget=new QStackedWidget;
_widget->addWidget(new QWidget);
_widget->addWidget(new GameWidgetView);
_widget->setStyleSheet("height: 400px; width: 500px;");
...
}

void MainWindow::newOnlineGame()
{
_widget->setCurrentIndex(1);
}

this is exactle what i need because i have a lot of widget to put on this stack :)

DanH
23rd May 2011, 00:40
There are several other ways you could do it. Simplest would be to parent the new widget with the old one and set the new widget's position to be (0,0) relative to the parent and its size to be the same as the parent. And, of course, don't forget to show() it.