Qt show modal dialog (.ui) on menu item click

c++, modal-dialog, qt

Solution

You need to setup the dialog with the UI you from your `.ui` file. The Qt `uic` compiler generates a header file from your `.ui` file which you need to include in your code. Assumed that your `.ui` file is called `about.ui`, and the Dialog is named `About`, then `uic`creates the file `ui_about.h`, containing a class `Ui_About`. There are different approaches to setup your UI, at simplest you can do

#include "ui_about.h"

...

void MainWindow::on_actionAbout_triggered()
{
    about = new QDialog(0,0);

    Ui_About aboutUi;
    aboutUi.setupUi(about);

    about->show();
}

A better approach is to use inheritance, since it encapsulates your dialogs better, so that you can implement any functionality specific to the particular dialog within the sub class:

AboutDialog.h:

#include <QDialog>
#include "ui_about.h"

class AboutDialog : public QDialog, public Ui::About {
    Q_OBJECT

public:
    AboutDialog( QWidget * parent = 0);
};

AboutDialog.cpp:

AboutDialog::AboutDialog( QWidget * parent) : QDialog(parent) {

    setupUi(this);

    // perform additional setup here ...
}

Usage:

#include "AboutDialog.h"

...

void MainWindow::on_actionAbout_triggered() {
    about = new AboutDialog(this);
    about->show();
}

In any case, the important code is to call the `setupUi()` method.

BTW: Your dialog in the code above is non-modal. To show a modal dialog, either set the `windowModality` flag of your dialog to `Qt::ApplicationModal` or use `exec()` instead of `show()`.

Problem

I want to make a simple 'About' modal dialog, called from Help->About application menu. I've created a modal dialog window with QT Creator (.ui file). What code should be in menu 'About' slot? Now I have this code, but it shows up a new modal dialog (not based on my about.ui): ``` void MainWindow::on_actionAbout_triggered() { about = new QDialog(0,0); about->show(); } ``` Thanks!

Original source

Related problems