You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Qt启用EnableHighDpiScaling后富文本图片被2倍拉伸,如何适配DPI?

解决Qt TextEdit富文本图片在HiDPI屏幕的尺寸适配问题

针对你遇到的问题,这里提供几个可行的解决思路:

1. 手动计算并指定图片显示尺寸

通过获取当前屏幕的设备像素比(DPR),手动调整富文本中img标签的width和height属性,让图片按原始物理尺寸显示。

示例代码:

#include <QGuiApplication>
#include <QScreen>

// 获取当前屏幕的设备像素比
qreal dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
// 假设test.png原始分辨率为200x150,计算适配后的显示尺寸
int showWidth = 200 / dpr;
int showHeight = 150 / dpr;

// 构造带尺寸的富文本内容
QString richContent = QString("<h1>Image test</h1><br/><img src='test.png' width='%1' height='%2'/>")
                      .arg(showWidth).arg(showHeight);

// 将内容设置给TextEdit
ui->textEdit->setText(richContent);

2. 拦截图片加载,自动选择HiDPI版本

通过自定义文件引擎处理器,拦截图片加载请求,根据屏幕DPR自动加载对应的@2x图片,同时配合Qt::AA_UseHighDpiPixmaps让Qt正确处理图片逻辑尺寸。

示例代码:

#include <QAbstractFileEngineHandler>
#include <QGuiApplication>
#include <QFile>

class HighDpiImageLoader : public QAbstractFileEngineHandler
{
public:
    QAbstractFileEngine* create(const QString& fileName) const override
    {
        qreal dpr = QGuiApplication::primaryScreen()->devicePixelRatio();
        // 仅当DPR≥2时尝试加载@2x版本
        if (dpr >= 2.0) {
            QString hiDpiPath = fileName.replace(".png", "@2x.png");
            if (QFile::exists(hiDpiPath)) {
                return QAbstractFileEngineHandler::create(hiDpiPath);
            }
        }
        // 没有HiDPI版本则加载原始图片
        return QAbstractFileEngineHandler::create(fileName);
    }
};

// 在main函数中注册处理器
int main(int argc, char* argv[])
{
    QGuiApplication app(argc, argv);
    // 启用HiDPI缩放和高DPI图片支持
    app.setAttribute(Qt::AA_EnableHighDpiScaling);
    app.setAttribute(Qt::AA_UseHighDpiPixmaps);

    HighDpiImageLoader imageLoader;

    // 后续初始化界面等逻辑
    return app.exec();
}

这样富文本中仍使用<img src='test.png'/>即可,处理器会自动匹配对应的HiDPI图片,且显示尺寸正常。

3. 利用Qt资源系统指定图片DPI

在Qt资源文件(.qrc)中为不同DPI的图片设置别名和dpi属性,让Qt自动根据屏幕DPI选择合适的图片。

资源文件示例:

<RCC>
    <qresource prefix="/">
        <file alias="test.png" dpi="96">test.png</file>
        <file alias="test.png" dpi="192">test@2x.png</file>
    </qresource>
</RCC>

配合启用Qt::AA_EnableHighDpiScaling和Qt::AA_UseHighDpiPixmaps,Qt会自动根据当前屏幕的DPI加载对应版本的图片,无需修改富文本内容。

内容的提问来源于stack exchange,提问作者fferri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 16:02:35