26

我想制作一个简单的“关于”模式对话框,从帮助->关于应用程序菜单中调用。我用 QT Creator(.ui 文件)创建了一个模态对话框窗口。

什么代码应该在菜单“关于”插槽中?

现在我有了这段代码,但它显示了一个新的模式对话框(不是基于我的 about.ui):

void MainWindow::on_actionAbout_triggered()
{
    about = new QDialog(0,0);
    about->show();
}

谢谢!

4

2 回答 2

41

您需要使用.ui文件中的 UI 设置对话框。Qtuic编译器从您的文件中生成一个头文件.ui,您需要将其包含在代码中。假设您的.ui文件被调用about.ui,并且对话框被命名About,然后uic创建ui_about.h包含一个类的文件Ui_About。有不同的方法来设置你的 UI,最简单的你可以做

#include "ui_about.h"

...

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

    Ui_About aboutUi;
    aboutUi.setupUi(about);

    about->show();
}

更好的方法是使用继承,因为它可以更好地封装您的对话框,以便您可以在子类中实现特定于特定对话框的任何功能:

关于Dialog.h:

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

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

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

关于Dialog.cpp:

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

    setupUi(this);

    // perform additional setup here ...
}

用法:

#include "AboutDialog.h"

...

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

无论如何,重要的代码是调用setupUi()方法。

顺便说一句:上面代码中的对话框是非模态的。要显示模态对话框,请将windowModality对话框的标志设置为Qt::ApplicationModalexec()使用show().

于 2012-10-29T07:08:55.980 回答
8

对于模态对话框,你应该使用exec()QDialogs 的方法。

about = new QDialog(0, 0);

// The method does not return until user closes it.
about->exec();

// In this point, the dialog is closed.

文档说:

显示模态对话框最常见的方法是调用它的exec()函数。当用户关闭对话框时,exec()会提供一个有用的返回值。


替代方式:您不需要模式对话框。让对话框显示无模式并将其accepted()rejected()信号连接到适当的插槽。然后,您可以将所有代码放在接受槽中,而不是将它们放在show(). 因此,使用这种方式,您实际上不需要模态对话框。

于 2015-06-21T20:46:49.093 回答