How to access parent widget pointer in QT

2019-07-27 12:45发布

问题:

I have a code something like this

Window::Window()
{
   QStackedWidget *centralApp = new QStackedWidget;
   QWidget1 *wgt1 = QWidget1;
   QWidget2 *wgt2 = QWidget2;
   QWidget3 *wgt3 = QWidget3;

   centralApp->addWidget(wgt1);
   centralApp->addWidget(wgt2);
   centralApp->addWidget(wgt3);
}

The classes QWidget1,QWidget2 and QWidget3 are inherited from QWidget and each contains two buttons btn1 and btn2. These buttons I want to use the two buttons in each widget to navigate to other two widgets added to stacked widget. So to navigate to other page in stacked widget I have to use the setCurrentIndex() and for this I need the parent QStackedWidget pointer. Can anybody suggest me how I can access the QStackedWidget pointer inside on of its page widgets to navigate to another page?

Please let me know if I am not clear in explaining the problem.

回答1:

I would have your subclasses emit a signal - 'next' and 'prev' for example - and then connect this signal in your main window to switch the QStackWidget's current widget.

Otherwise, you're tightly coupling your stacked widgets in a way that is unnecessary.



回答2:

http://doc.qt.io/archives/4.6/qwidget.html#parentWidget

(centralApp==wgt1->parentWidget()) //true