tom
tom

Reputation: 1344

Qt creating MDI document window

I am trying to create a MDI document program. I have a question on creating the subwindow.

This is my mainwindow constructor:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle(tr("MDI"));

    workspace = new QMdiArea;
    setCentralWidget(workspace);
    //fileNew();

    createActions();
    createMenus();
    createToolbars();

    statusBar()->showMessage(tr("Done"));

    enableActions();
}

The interesting point is the fileNew(); function. It is a private slot function actually which I want to invoke when "New File" button is triggered. Here is the private slot fileNew() function:

void MainWindow::fileNew()
{
    DocumentWindows* document = new DocumentWindows;
    workspace->addSubWindow(document);
}

This function works perfectly when I call from the mainwindow constructor. However, there is a problem when I call it from the createActions(); function which uses a signal-slot mechanism.

Here is my createActions()

void MainWindow::createActions()
{
    newAction = new QAction(QIcon(":/Image/NewFile.png"),tr("&New"),this);
    newAction->setShortcut(tr("Ctrl+N"));
    newAction->setToolTip(tr("Open new document"));
    connect(newAction, SIGNAL(triggered(bool)), this, SLOT(fileNew()));
}

No subwindow is created even the SLOT is triggered. Subsequently, I find out that if I add document->show();, everything works well.

void MainWindow::fileNew()
{
    DocumentWindows* document = new DocumentWindows;
    workspace->addSubWindow(document);
    document->show();
}

My question is: Why the show() function is needed in a SLOT but not in the constructor?

PS. DocumentWindows is just a class inherits QTextEdit.

Upvotes: 2

Views: 2774

Answers (1)

This problem has nothing to do with the class of the widgets one is using. It is unrelated to documents, MDI, or the main window. After you add a child widget to a widget that is already visible, you must explicitly show it. Otherwise, the widget will remain hidden.

All widgets are hidden by default. When you initially show the MainWindow, all of its children are recursively shown too. When you later add a child MDI widget, it remains hidden. When widgets are added to layouts, they are shown by default - but your widget is managed by the MDI area, not by a layout.

This is a minimal test case demonstrating your issue:

// https://github.com/KubaO/stackoverflown/tree/master/questions/widget-show-32534931
#include <QtWidgets>

int main(int argc, char ** argv) {
    QApplication app{argc, argv};
    QWidget w;
    w.setMinimumSize(200, 50);
    QLabel visible{"Visible", &w};
    w.show();
    QLabel invisible{"Invisible", &w};
    invisible.move(100, 0);
    return app.exec();
}

Upvotes: 1

Related Questions