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

人盡茶涼 提交于 2019-12-20 09:49:12

问题


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!


回答1:


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 uiccreates 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().




回答2:


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.



来源:https://stackoverflow.com/questions/13116863/qt-show-modal-dialog-ui-on-menu-item-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!