9

With functions

QApplication::desktop()->screenCount();
QApplication::desktop()->screenGeometry();

I find how much screens exist on my system and on which screen coordinates they are located. Now I want to find out on which screen a QWidget is located at. How can I do that? Do I have to check the coordinates of the QWidget against the screen-coordinates or is there a more elegant way for this which returns the screen-number directly?

cigien
  • 57,834
  • 11
  • 73
  • 112
Elmi
  • 5,899
  • 15
  • 72
  • 143

4 Answers4

17

QDesktopWidget is deprecated in newer Qt versions (5.11 and above, not deprecated in 5.10).

Since Qt 5.10 there is QGuiApplication::screenAt(QPoint) as a replacement for screenNumber(QPoint).

Seems there is no direct replacement for screenNumber(QWidget*). However, it is possible to get information about the screen where the widget in question is located through QScreen pointer:

QScreen *screen = widget->window()->windowHandle()->screen();
qDebug() << screen->geometry()
                << screen->availableGeometry();
Silicomancer
  • 8,604
  • 10
  • 63
  • 130
  • 2
    somehow that doesn't work for me (Windows, Qt5.13). – Zord Oct 25 '19 at 08:23
  • 1
    Why on earth is `screenNumber` deprecation documentation on Qt docs not LINKING to screenAt? This would have saved me quite some time. Thank you! – IceFire Mar 22 '22 at 06:56
7

I think the function you should be looking for is this

int QDesktopWidget::screenNumber(const QPoint &point) const

This is an overloaded function. Returns the index of the screen that contains the point, or the screen which is the shortest distance from the point.

since i don't have multiple screens, you can check for yourself, the QWidget::pos() function provides the QPoint

Edit: As suggested by scopchanov in comments, you can also use

QDesktopWidget::screenNumber(const QWidget *widget = Q_NULLPTR)
Gurushant
  • 952
  • 6
  • 23
6

In addition to Sillicomancers answer, I use the following code to replace the depricated QDesktopWidget::availableGeometry(const QWidget *widget)

QScreen* pScreen = QGuiApplication::screenAt(widget->mapToGlobal({widget->width()/2,0}));
QRect availableScreenSize = pScreen->availableGeometry();

which uses the screen where the middle of the top of widget is located.

Zord
  • 926
  • 11
  • 11
5

QWidget::screen() introduced in Qt5.14.

cigien
  • 57,834
  • 11
  • 73
  • 112
Kao
  • 537
  • 5
  • 12