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!
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()
.
For modal dialogs, you should use exec()
method of QDialogs.
about = new QDialog(0, 0);
// The method does not return until user closes it.
about->exec();
// In this point, the dialog is closed.
Docs say:
The most common way to display a modal dialog is to call its
exec()
function. When the user closes the dialog,exec()
will provide a useful return value.
Alternative way: You don't need a modal dialog. Let the dialog show modeless and connect its accepted()
and rejected()
signals to appropriate slots. Then you can put all your code in the accept slot instead of putting them right after show()
. So, using this way, you wouldn't actually need a modal dialog.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With