Important: Please read the Qt Code of Conduct -


  • Hello,
    I am getting back into C++ after a long time. I want to create a singleton of a QMdiSubWindow. My goal is to basically show only one instance of the sub window.

    The constructor for the MdiSubWindow looks like this:

    SubWindow::SubWindow(QWidget *parent) : QMdiSubWindow(parent)

    During regular instantiation (without singleton), I use:

    SubWindow*childWindow = new SubWindow(ui->mdiArea);

    In order to create a singleton of SubWindow, in the SubWindow.cpp I would use:

    Q_GLOBAL_STATIC_WITH_ARGS(SubWindow, uniqueInstance, <args>)

    and then call

    Q1: Am I on the right track?
    Q2: What would the Q_GLOBAL_STATIC_WITH_ARGS line look like?

    Appreciate your help.

  • Lifetime Qt Champion

    Hi and welcome to the forums.
    Can you explain why you want to make a singleton out of a QMdiSubWindow.
    Im asking as once inserted into MDI area, the area owns it and it cannot be used any place else so
    i not sure what you would gain by using it as singleton.

  • Hello,
    When the menu/action is clicked, a new subwindow is opened. I want only one instance of the subwindow to be opened. If it has not been opened at all, then instantiate the singleton and show it. If it has already been instantiated, get the instance and show it.

    In any case, I realized the macros are expanded at compile time. Just wrote vanilla C++ singleton code.

    Thanks, JG

  • Lifetime Qt Champion

    Why not just make
    SubWindow*childWindow=0; a member of the mainwindow
    if (! childWindow) childWindow= new SubWindow(ui->mdiArea);

    That way, you will only create it once. and no need for macros and singleton pattern etc.

Log in to reply