I have a base class MainWindow
which inherits from QMainWindow
.
MainWindow
has QSTackedWidget
in its Ui file. I have Page1
and Page2
in different classes All page widgets in there are seperate classes derived from QWidget
.
QMainWindow
implements QStackedWindow
in one class. All other pages inside the stacked widget are added classes and all have there own .ui filled with buttons
I implemented
Page1* page1obj = new Page1;
Page2* page2obj = new Page2;
ui->stackedWidget->insertWidget(0,page1obj);
ui->stackedWidget->insertWidget(1,page2obj);
it has a ui file which has next button . On clicked it should be go to page 2;
Page1.cpp
connect(m_ui>nextButton,&QPushButton::clicked,this,&Page1::onclicked);
void Page1::onclicked()
{
Mainwindow* obj = new MainWindow;
obj->openPage2();
}
The issue is on clicked button opens up a new window, not a single window in stacked format. Where am I going wrong?? How to fix this issue?
It is not necessary to make the change in MainWindow, you can do it from the pages.
When you insert a widget into a QStackedWidget
, this is set as the parent widget, so we can access QStackedWidget
with the parentWidget()
method:
void Page1::onclicked()
{
QStackedWidget *stack = qobject_cast<QStackedWidget* >(parentWidget());
if(stack)
stack->setCurrentIndex(1);
}
Update:
If you want to use MainWindow
you do not have to create a MainWindow
, but access it using the parental relationship and in the end make a casting
mainwindow
└── stackedwidget
├── page1
└── page2
void Page1::onclicked()
{
MainWindow *mainwindow = qobject_cast<MainWindow* >(parentWidget()->parentWidget());
if(mainwindow)
mainwindow->openPage2();
}