ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

QT 高DPI解决方案

2026/9/28 2:27:53 拓冰建站 浏览量
QT 高DPI解决方案

一、根据DPI实现动态调整控件大小(三种方式)

1、QT支持高DPI(针对整个进程中所有的UI)

// main函数中
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling)

tips:(1)如果不想全局设置,可以使用下面两种方式进行单独设置。(2)如果想有的窗口使用系统高DPI缩放,有的窗口保持DPI,就需要设置该属性,并修改QT源码,增加接口,来判断某个窗口是否需要高DPI自动缩放

2、存在该头文件<QtWidgets/private/qstylehelper_p.h>

#include <QtWidgets/private/qstylehelper_p.h>qreal KStyle::dpiScaled(qreal value)
{
#ifdef Q_OS_MAC// On mac the DPI is always 72 so we should not scale itreturn value;
#elsereturn QStyleHelper::dpiScaled(value);
#endif
}

3、不存在该头文件<QtWidgets/private/qstylehelper_p.h>,自己实现

#include <QScreen>qreal KStyle::dpiScaled(qreal value)
{
#ifdef Q_OS_MAC// On mac the DPI is always 72 so we should not scale itreturn value;
#elseqreal dpi = QGuiApplication::primaryScreen()->logicalDotsPerInch(); static const qreal scale = qreal(dpi) / 96.0;return value * scale;
#endif
}

二、使用示例

ui->btnClose->setFixedHeight(dpiScaled(ui->btnClose->minimumHeight()));