Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

get mainwindow size?



  • All windows can be obtained from QGuiApplication::allWindows(). The main window can be found with a loop over all windows. Then its size can be obtained.

    Is there any easier way to get mainwindow size of a Qt app? I need it deep in my Qt app.



  • @JoeCFD
    In a word, "No". If you need to access the main window (or any other window) from deep down in code you do need a helper function like you have found. You can make yours (maybe) a bit faster: I used QGuiApplication::topLevelWindows() for top-level only (no parent) as that will be what main window is, I don't know if Qt can produce that faster than allWindows().

    I found it fine, speed-wise. Of course if you do it a lot you could always cache the result fur re-use.

    I prefer this to saving some "globally accessible variable" which you set with the main window when you first create it. But of course that would be fast.



  • @JoeCFD
    Hi.
    I never did this, but a possible workaround is:

    In your virtual void QMainWindow::resizeEvent(QResizeEvent *event); you can store the size of application in variables where all your code can access them.

    It is only an idea! :)



  • @CP71 Unluckily global variables are not encouraged.



  • @JonB Thanks for your reply. I tried both which are same in my app. No overhead issue. I expected to use one func call to get it. I will mark my post as solved.



  • @JoeCFD said in get mainwindow size?:

    Unluckily global variables are not encouraged.

    Correct!
    No global variables, somewhere like a core manager, view manager, data manager and so on. Objects that normally are visible quite everywhere. ;)


  • Lifetime Qt Champion

    Hi,

    Out of curiosity, why do you need that information deep in your code ?



  • @SGaist I need to pop-up some dialogs and their sizes are scaled with mainwindow size. The sizes of dialogs and their children are set by professional UI designers.


Log in to reply