Zmicier
Zmicier

Reputation: 81

Create a new window in Qt which depends on the parent window, but appears outside of the parent window

I want to implement a log for my application, and I want it to be in another window. But of course it should close when the main window is closed.

The main window is created with class Window which inherits from QWidget.

When I create the second window the same way and pass into the constructor "this" as parent, that does not work, everything that is inside new window appears inside parent window. But when I don't pass anything into the constructor of new window, it does not close when the parent window closed.

Upvotes: 7

Views: 4020

Answers (2)

bhaller
bhaller

Reputation: 2137

As @hyde commented, you should set Qt::Window for the window flags when you create the window widget, and then you can give it a parent and it will be a "secondary window" and will close when the parent closes. Inheriting from QDialog is fine, but brings along additional baggage that you may not want/need; the simple answer to the question is to use Qt::Window.

Upvotes: 3

Alexey Tsybin
Alexey Tsybin

Reputation: 220

Try to create the second window which inherits from QDialog.

#ifndef FORM_H
#define FORM_H

#include <QDialog>

namespace Ui {
class Form;
}

class Form : public QDialog
{
    Q_OBJECT

public:
    explicit Form(QWidget *parent = 0);
    ~Form();
private slots:

private:
    Ui::Form *ui;
};

#endif // FORM_H

And MainWindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QDebug"
#include "form.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(showNewWindow()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::showNewWindow()
{
    Form *form;
    form = new Form(this);
    form->setModal(false);
    form->show();
}

Upvotes: 2

Related Questions