0

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

0

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.";
  }
}
G.M.
  • 12,232
  • 2
  • 15
  • 18
  • Pointing out the use of the QUiLoader is what I was missing. This solution works perfectly as describes. The biggest consideration with this solution is knowing the proper directory both when using the Qt Creator and running standalone. – Mike Wells Apr 09 '21 at 15:24