Important: Please read the Qt Code of Conduct -

Find the active QScreen of any QWidget

  • Hi, Is there an easy way to find a widget's active QScreen it resides on, obviously in a multi display environment. I am using Qt5.8 on windows 10.

    I have extended the desktop with with an additional monitor which has lower resolution then my laptop.
    This gives me some scaling issues with QPicture I am trying to work around.
    I tried the function windowsHandle() which has a function screen but this function returns zero, propably because my widget is not a top level widget but instead part of an MDI child.

  • Lifetime Qt Champion

    Could you not you use
    "Returns the index of the screen that contains the largest part of widget"

  • Hi, Thanks for your suggestion. I tried this but this always returns 0. This is correct though, I extended my desktop so there is always one virtual screen.
    But then again QDesktopWidget::screenCount() return 2. So this is a bit odd.

  • I found this in the docu:

    "virtualDesktop : const bool
    This property holds if the system manages the available screens in a virtual desktop.
    For virtual desktops, screen() will always return the same widget. The size of the virtual desktop is the size of this desktop widget."

    So... yep virtualDeskTop() returns true.

  • Lifetime Qt Champion

    Ok, i think you need to loop over the screens and their geometry and
    check that against the apps x,y to see on which screen it is placed.
    if its x are bigger than screen 0 width, then its on screen 1.

    Notice, that apps. x might be negative. At least thats the case when placing
    remote desktop windows and second monitor is on the left. . I didn't test
    what Qt reports in this case.

    Technically its one big screen so hence screenNumber reports correctly.
    Sorry, i missed the "extended" word in your description. :)

  • This works ok. But not every widget has a windowHandle (maybe olny top level ones?) So then i grab the parent to check it.

    QScreen* getActiveScreen(QWidget* pWidget) const
    			QScreen* pActive = nullptr;
    			while (pWidget)
    				auto w = pWidget->windowHandle();
    				if (w != nullptr)
    					pActive = w->screen();
    					pWidget = pWidget->parentWidget();
    			return pActive;

  • Lifetime Qt Champion

    ok so for a top level widget/window, ->screen()
    actually knows which screen even if its a virtual screen/extended.
    That is good to know :)
    Its explained here whom have >windowHandle();

Log in to reply