Why is the recommended QDialog instantiation the way it is?

时间:2016-07-11 22:54:10

标签: c++ qt

I have a Qt Widgets application, created and edited in Qt-Creator.

The main window (MainWindow class) has a menubar, with a button to open a small dialog (with text or widgets for settings).

To create a new "window" I open the "create new file" dialog in Qt-Creator and select Qt Designer Form Class, which creates the needed header, source, and ui files (dialogabout.h, dialogabout.cpp, dialogabout.ui).

If I follow along with the docs, I then open the QDialog like so:

QDialog * widget = new QDialog;
Ui::DialogAbout about_ui;
about_ui.setupUi(widget);
widget->exec();

This works, but if I modify the new dialog's instantiator to connect a pushbutton to the close signal, the connect statement (along with any other code there) is never reached.

DialogAbout::DialogAbout(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogAbout)
{
    ui->setupUi(this);

    qDebug() << "I'm alive!"; // No output happens
    connect(ui->pushButton_close, SIGNAL(clicked(bool)), this, SIGNAL(please_close())); // No signal created on pushbutton click.
}

I suspect that this is because I haven't explicitly done widget = new DialogAbout(this). If I instead instantiate the new dialog this different way:

DialogAbout * newwindow;
newwindow = new DialogAbout(this);
newwindow->exec();

Then the connect statement and qDebug work.

My question is: what are the pitfalls of deviating from the documentation's recommended way to create dialogs? Is there a way to get this functionality with the prior instantiation method?

1 个答案:

答案 0 :(得分:1)

请注意,DialogAbout与Ui :: DialogAbout不同。 Ui :: DialogAbout是一个放置在UI名称空间中的构建类,由uic自动创建。在您的项目中,此文件的名称应为&#34; ui_dialogabout h&#34;。

class Ui_DialogAbout
{
public:
    QPushButton *pushButton_close;

    void setupUi(QDialog *DialogAbout)
    {
        ...
    } // setupUi

    void retranslateUi(QDialog *DialogAbout)
    {
        ...
    } // retranslateUi

};
namespace Ui {
    class DialogAbout: public Ui_DialogAbout {};
} // namespace Ui

这里使用类QDialog并使用Ui :: DialogAbout在其中构建布局。请注意,Ui :: DialogAbout具有在QDialog中创建组件的功能。

QDialog * widget = new QDialog;
Ui::DialogAbout about_ui;
about_ui.setupUi(widget);
widget->exec();

如果您专注于DialogAbout的QDialog,您的代码应如下所示:

DialogAbout * widget = new DialogAbout();
Ui::DialogAbout about_ui;
about_ui.setupUi(widget);
widget->exec();

但是由于setupUi()已经在DialogAbout中,你不能再次调用,导致:

DialogAbout * widget = new DialogAbout();
widget->exec();