商城首页欢迎来到中国正版软件门户

您的位置:首页 >QT获取主屏幕DPI方法解析

QT获取主屏幕DPI方法解析

  发布于2025-07-15 阅读(0)

扫一扫,手机访问

在DpiAware设置为SystemAware的情况下,获取主屏幕的DPI值是必要的。DPI(Dots Per Inch)表示每英寸的点数,通常用于描述屏幕分辨率。在Windows操作系统中,DPI感知(DPI Awareness)指的是应用程序能够识别屏幕的DPI设置,并根据DPI值调整其界面元素的大小和布局,以提供更好的用户体验。

DPI感知有两种模式:系统DPI感知和每个监视器DPI感知。

系统DPI感知(System aware)指的是应用程序根据整个系统的DPI设置来调整其界面元素的大小和布局。这种模式下,当用户更改系统DPI设置时,所有应用程序的界面都会相应地调整。

每个监视器DPI感知(Per Monitor)指的是应用程序能够检测到每个显示器的DPI设置,并根据每个显示器的DPI值分别调整其界面元素的大小和布局。这种模式下,当用户在不同DPI设置的显示器之间移动应用程序窗口时,应用程序的界面会自动适应每个显示器的DPI设置。

在实现DPI感知时,需要确保应用程序的界面元素能够正确地缩放,以避免在高DPI设置下出现模糊或过小的情况。

在使用每个监视器DPI感知时,需要注意处理不同显示器之间的DPI变化,以确保应用程序的界面在不同显示器之间保持一致。

在编写DPI感知应用程序时,建议使用支持高DPI的UI框架,如Windows Presentation Foundation (WPF)或Qt等。

Qt应用程序为了默认支持高清屏,设置的DPI感知类型为Per Monitor,以下是5.15.2版本的源码:

时机为程序创建第一个窗口之前,所以需要修改DPI感知类型需要在这个时机之前,否则会有警告提示设置失败。

代码语言:C

// Src\qtbase\src\plugins\platforms\windows\qwindowsintegration.cpp
QWindowsIntegrationPrivate::QWindowsIntegrationPrivate(const QStringList &paramList)
{
    initOpenGlBlacklistResources();
    static bool dpiAwarenessSet = false;
    int tabletAbsoluteRange = -1;
    // Default to per-monitor awareness to avoid being scaled when monitors with different DPI
    // are connected to Windows 8.1
    QtWindows::ProcessDpiAwareness dpiAwareness = QtWindows::ProcessPerMonitorDpiAware;
    m_options = parseOptions(paramList, &tabletAbsoluteRange, &dpiAwareness);
    QWindowsFontDatabase::setFontOptions(m_options);
    if (m_context.initPointer(m_options)) {
        QCoreApplication::setAttribute(Qt::AA_CompressHighFrequencyEvents);
    } else {
        m_context.initTablet(m_options);
        if (tabletAbsoluteRange >= 0)
            m_context.setTabletAbsoluteRange(tabletAbsoluteRange);
    }
    if (!dpiAwarenessSet) { // Set only once in case of repeated instantiations of QGuiApplication.
        if (!QCoreApplication::testAttribute(Qt::AA_PluginApplication)) {
            m_context.setProcessDpiAwareness(dpiAwareness);
            qCDebug(lcQpaWindows) 

在Windows上主动设置Qt应用的DPI感知,需要判断系统不低于Windows 8.1。

代码语言:C

if (QOperatingSystemVersion::current() 

在默认的Qt程序下,获取主屏幕DPI需要先调整DPI感知类型然后再获取,否则会拿到错误的DPI值,主要利用SHCore.dll和User32.dll两个系统模块,系统不低于Windows 8.1。

话不多说,直接上代码,仅供参考学习:

代码语言:C

bool GetPrimaryMonitorDpi(float &dpi) {
    bool bRes = false;
    HMODULE shcoreModule = nullptr;
    do 
    {
        if (QOperatingSystemVersion::current() 

【QT】获取主屏幕DPI

本文转载于:https://cloud.tencent.com/developer/article/2449444 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注