How get actual device screen width in pixels

  • I need the actual screen dimensions in pixels running in mac os. A little research suggests I want to make the call:

    #if defined(Q_OS_MAC)
    int screenWidth = CGDisplayPixelsWide(CGMainDisplayID());

    However, I need a header file to make this work (if this is the correct call). Can anyone help me with the header I need or another approach to get this info. Thanks in advance.

  • Okay, I got it to work by adding

    mac:LIBS += -framework ApplicationServices

    to my .pro file and using the header

    #include <ApplicationServices/ApplicationServices.h>

    However, this returned 1920 pixels, the same as Qt does in QScreen. This is the virtual pixels reported by Mac OS. Any ideas on getting the actual number of device pixels (2880 in my case)?

  • It appears what I need is in NSScreen backingScaleFactor. I've just learned what a .mm file is and I don't know anything about object c. How do I access the backingScaleFactor from my Qt c++ mainwindow class?

  • Lifetime Qt Champion


    That's Objective-C++, you can take a look at the QtMacExtras framework as a simple base on how to use that.

  • @SGaist

    Thanks for the guidance. :*)

  • I've given objective c a try but I'm getting a "expected unqualified-id" error:

    expected unqualified-id >>>>>>>>>>>>>>>>>>>>>>>>>>>NSObjRuntime.h
    @class NSString, Protocol;

    My Qt calling class header includes

    #include <MacOs/macscale.h>


    #ifndef MACSCALE_H
    #define MACSCALE_H
    #include <QtCore/qglobal.h>
    #import <Foundation/Foundation.h>
    namespace QtMac {
    Q_DECL_EXPORT CGFloat macBackingScaleFactor();
    }  // namespace QtMac
    #endif // MACSCALE_H


    #include "MacOS/macScale.h"
    #import "macScale.h"
    #import <AppKit/AppKit.h>
    namespace QtMac {
    CGFloat macBackingScaleFactor() {
        return [[NSScreen mainScreen] backingScaleFactor];
    }  // namespace QtMac

    I've added to my pro file


    And finally, in the Qt calling class I use

    QVariant bSF = QtMac::macBackingScaleFactor();

    Any ideas on what I'm doing wrong?

  • Lifetime Qt Champion

    The idea of Objective-C++ is to shield the interface from the Objective-C part.

    Remove the import statement from your header and use float as return type.

    By the way, your use of the Q_DECL_EXPORT macro is wrong. Take a look at its documentation for the correct use.

  • @SGaist
    Thanks. I really appreciate the help. Back to the books!

  • @SGaist said in How get actual device screen width in pixels:


    I got it to work. I was missing this line in my pro file:

    mac:LIBS += -framework AppKit

    As always, the help is very much appreciated. Have a great time over the holiday season!

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.