Qt 5, get the mouse position in a screen

前端 未结 6 1332
难免孤独
难免孤独 2020-12-17 10:37

First of all, I\'d like to mention that I found that related post How to get the mouse position on the screen in Qt? but it \"just didn\'t work\" for me. I made some tests,

6条回答
  •  心在旅途
    2020-12-17 11:12

    To figure out on which screen you are, you can iterate throught QGuiApplication::screens() and check whether the cursor fits in the geometry of the screen.

    Here is a more complex example to compute the native cursor position (note the additional work needed to work with High DPI screens):

    QPoint getNativeCursorPosition()
    {
        QPoint pos = cursorPosToNative(QCursor::pos());
    
        // Cursor positions from Qt are calculated in a strange way, the offset to
        // the origin of the current screen is in device-independent pixels while
        // the origin itself is native!
    
        for (QScreen *screen : QGuiApplication::screens()) {
            QRect screenRect = screen->geometry();
            if (screenRect.contains(pos)) {
                QPoint origin = screenRect.topLeft();
                return origin + (pos - origin) * screen->devicePixelRatio();
            }
        }
    
        // should not happen, but try to find a good fallback.
        return pos * qApp->devicePixelRatio();
    }
    

提交回复
热议问题