dosvarog
dosvarog

Reputation: 754

Application with multiple windows in Qt

What is a good way to create application with multiple windows in Qt? Something like GIMP. I have already read this answer and it is not what I need.

I have two windows, one with controls and one with OpenGL inside. Right now I have something like this:

int main()
{
    // some code

    MainWindow mw;
    mw.show();

    GLWindow gw;
    gw.show();

    // ...
}

I don't like this for two reasons. First reason is when I start my application, window with OpenGL will be on top (because it is last to call show()) but MainWindow will be buried somewhere under all opened windows. What I need is both windows in front of everything (like GIMP), preferably with focus on MainWindow (I guess I can bring them to front, so that is minor issue). Second reason I don't like this is that my application will be closed completely only when I close both windows.

So I was thinking of having a reference to GLWindow inside MainWindow, and creating it from MainWindow.

Would that be a good way to create application with several windows?

EDIT: GLWindow inherits from QOpenGLWindow.

Upvotes: 0

Views: 2764

Answers (2)

Saeed Sayyadipour
Saeed Sayyadipour

Reputation: 550

You are doing right, but with the following simple tricks, you can resolve both issues that cause you do not like your right method:

  1. To activate both windows, just do as follows:
    MainWindow mw;
    mw.show();
    mw.activateWindow();

    GLWindow gw;
    gw.show();
    gw.activateWindow();
  1. To resolve the quit problem, you have to override the closeEvent in both windows. To do that, add the following code into the header file of your both windows:
protected:
    void closeEvent(QCloseEvent *event) override;

and in the implementation of the closeEvent, just write qApp->quit();. This way once you close either window, your application will terminate completely.

MainWindow.cpp

void MainWindow::closeEvent(QCloseEvent *event)
{
    qApp->quit();
}

and

GLWindow.cpp

void GLWindow::closeEvent(QCloseEvent *event)
{
    qApp->quit();
}

Upvotes: 2

G.M.
G.M.

Reputation: 12898

I'm not sure I completely understand the situation but, typically, you can make the 'secondary' widgets child dialogs of the QMainWindow. Given your example code that would be something like...

int main ()
{
    // some code

    MainWindow mw;
    mw.show();

    /*
     * Secondary windows should be created with the QMainWindow mw
     * as their parent.
     */
    GLWindow gw(&mw);

    /*
     * Set the Qt::Dlaog window flag to `encourage' the QMainWindow
     * and its children to behave as a group.
     */
    gw.setWindowFlags(gw.windowFlags() | Qt::Dialog);
    gw.show();

    // ...
}

Now all widgets behave as a group (possibly subject to the window manager being used) and closing the QMainWindow will, by default, close the application.

Upvotes: 1

Related Questions