Switch screens (.ui) on same window without opening new window with C++
-
How to open multiple UI screen on same window with pushbutton click (without opening new window)? when I click button on first.ui, it should bring second.ui and when I click pushbutton on second.ui, it shoud bring first.ui, wthout opening new window. I have found information about doing this on PyQt5 but I want to do it in c++, can someone help me in this regards, also please share a sample code as I can know, I am beginner, i might need example code to understand.
Thanks! -
Syntax aside, this is the same in C++ or Python.
The cleanest method is to put the two widgets, one for each Designer form, in a QStackedWidget and switch between them with the QPushbuttons (or whatever other mechanism you like). Alternatively use a QTabWidget to contain the two forms.
-
Hi
You just place the QStackedWidger on the main window.
Then right-click and use "Add page"Then on the buttons where you want to switch between the pages,
you call
ui->stackedWidget->setCurrentIndex(1);
with index 0 or 1 to switch between the pages.And that is it :)
-
Complete example with dummy page widgets. This, I think, is a better example than the Python in the video.
#include <QApplication> #include <QWidget> #include <QVBoxLayout> #include <QStackedWidget> #include <QPushButton> #include <QLabel> class Page1: public QLabel { Q_OBJECT public: Page1(QWidget *p = nullptr): QLabel(p) { setText("Screen 1"); } }; class Page2: public QLabel { Q_OBJECT public: Page2(QWidget *p = nullptr): QLabel(p) { setText("Screen 2"); } }; class MainWindow: public QWidget { Q_OBJECT public: MainWindow(QWidget *p = nullptr): QWidget(p) { QVBoxLayout *layout = new QVBoxLayout(this); m_stack = new QStackedWidget(this); layout->addWidget(m_stack); QWidget *page1 = new Page1(m_stack); m_stack->addWidget(page1); QWidget *page2 = new Page2(m_stack); m_stack->addWidget(page2); QPushButton *button = new QPushButton("Switch page", this); layout->addWidget(button); connect(button, &QPushButton::clicked, this, &MainWindow::switchPage); } public slots: void switchPage() { if (m_stack->currentIndex() == 0) m_stack->setCurrentIndex(1); else m_stack->setCurrentIndex(0); } private: QStackedWidget *m_stack; }; int main(int argc, char **argv) { QApplication app(argc, argv); MainWindow mainWindow; mainWindow.show(); return app.exec(); } #include "main.moc"