Search code examples
c++qtqwidgetqt-designerqtgui

Qt Using a Ui file and QUiLoader


I am developing an c++ application using Qt. I want to use the Qt Designer ui file in my code as it is (in XML) not compiling the code and hard coding it. I am using the example code from this URL.

link to example code

The example applies the XML to a QWidget and then displays the QWidget. How can this be implemented using QMainWindow, keeping in mind that I selected the Main Window form in Qt Designer which already adds a central widget?


Solution

  • There are at least two ways to do that.

    Way 1

    Use Qt Designer to add a vertical layout to the central widget. You can't do that for a widget with no children, so just add a button, apply the layout and delete that button. Give your layout a good name e.g. "main_layout".

    Copy constructor implementation from the example and change these lines:

    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(formWidget);
    setLayout(layout);
    

    to this:

    ui->main_layout->addWidget(formWidget);
    

    Way 2

    You don't need to manipulate with the main window's form. Just copy constructor implementation from the example and change the same lines about layout to this:

    setCentralWidget(formWidget);
    

    The automatically generated central widget will be completely replaced with the dynamically loaded form.