1

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?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Rubina
  • 123
  • 1
  • 17

1 Answers1

0

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();
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • I need to send signal to Mainwindow.cpp to change to index to 1 . But using new operator it opens a up the Page2 as new pop up window rather than swapping from parent window to page 2 – Rubina Mar 31 '18 at 04:58
  • @Rubina Why do you need to send it to MainWindow ?, have you tried my solution? – eyllanesc Mar 31 '18 at 05:01
  • MainWindow has the QStackedWidget and has all the pages in it so I need to send signal to Mainwindow to swap back and forth – Rubina Mar 31 '18 at 05:04
  • @Rubina I have added another possible solution: – eyllanesc Mar 31 '18 at 05:08
  • I tried your solution . it works well from moving from page 1 to page 2 but is becomes irresponsive from page 2 to page 3 or page 2 to 1 – Rubina Mar 31 '18 at 05:10