Using QFileDialog with QWindow

340 Views Asked by At

I try to implement an application with OpenGL, so as the following example suggested, I used an QWindow to create an OpenGL context.

http://doc.qt.io/qt-5/qtgui-openglwindow-example.html

In this application, I want to create a file dialog when I press S key. However, QFileDialog::getSaveFileName requires a parent of QWidget. The documentation says if parent is 0, the dialog will be shown centered over the parent widget. I wonder in this case it is ok to simply use nullptr as parent.

Example:

#include <QApplication>
#include <QMainWindow>
#include <QKeyEvent>
#include <QDebug>
#include <QFileDialog>
#include <QtGui/QWindow>

class DisplayWindow final : public QWindow
{
    Q_OBJECT

public:
    DisplayWindow(QWindow* parent = 0)
        : QWindow(parent)
    {
        // Setup OpenGL context
        // ...
    }

protected:
    virtual void keyPressEvent(QKeyEvent* event) override
    {
        if (event->key() == Qt::Key_S)
        {
            //                                          ???????
            QString path = QFileDialog::getSaveFileName(nullptr, "Save", "", "");
            qDebug() << path;
        }
    }

};

class MainWindow final : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0)
        : QMainWindow(parent)
    {
        displayWindow = new DisplayWindow;
        auto* container = QWidget::createWindowContainer(displayWindow, this);
        container->setMinimumSize(200, 200);
        setCentralWidget(container);
    }

private:
    DisplayWindow* displayWindow;

};

int main(int argc, char** argv)
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

#include "moc_test.cpp"
1

There are 1 best solutions below

0
On

Yeah, it should be safe. Since you do not dynamically allocate memory you don't have to delete anything. If you set up parents, Qt will delete the widgets on its own. In here it just has affects on the window modality and position. If you want to set a parent, you could just use "this" in your context.