c++qtqt-designerqstackedwidget

Is it possible to have each page of a Stacked Widget specified in a separate ui file


I am using the Stacked Widget in Qt Creator v4.14.2. Right now all of the items for each page reside in the mainwindow.ui file. I do not have a problem switching between pages.

I am wanting to put the items for each Stacked Widget page in a separate ui file for clarity and file size reasons. I understand that there is not a technically reason for this need. I have developed UIs using MVVM and would like to replicate that methodology in Qt (using Qt Creator) if at all possible.

For this project I am working on, I would prefer not do page and/or Widget creation in the C++ code.


Solution

  • You can load as many UI files as you need using QUiLoader. Assuming the files are named page-1.ui, ... page-10.ui you could have something like (untested)...

    #include <QStackedWidget>
    #include <QUiLoader>
    #include <QWidget>
    
       .
       .
       .
    
    QStackedWidget stack;
    QUiLoader loader;
    for (int page_no = 1; page_no <= 10; ++page_no) {
      QFile f(QString("page-%1.ui").arg(page_no));
      if (f.open(QFile::ReadOnly)) {
        auto *w = loader.load(&f);
        stack.addWidget(w);
      } else {
        qWarning() << "failed to load UI file.";
      }
    }