Programming/qt

qt 동적 해상도 대응

구차니 2026. 6. 29. 14:57

열심히 AI 갈구면서 테스트

 

아래의 클래스 추가

// UIScale.h
#pragma once

#include <QWidget>

namespace UIScale
{
    void scale(QWidget *w);
    void scaleTree(QWidget *root);
}

 

// UIScale.cpp

#include "UIScale.h"

#include <QGuiApplication>
#include <QScreen>
#include <QDebug>

namespace
{
    constexpr int BASE_WIDTH  = 800;
    constexpr int BASE_HEIGHT = 480;
}

void UIScale::scale(QWidget *w)
{
    if (!w)
        return;

    // 이미 적용했으면 종료
    if (w->property("_scaled").toBool())
        return;

    QScreen *screen = QGuiApplication::primaryScreen();
    if (!screen)
        return;

    QSize screenSize = screen->availableGeometry().size();

    const double sx = double(screenSize.width())  / BASE_WIDTH;
    const double sy = double(screenSize.height()) / BASE_HEIGHT;

    QRect r = w->geometry();

    w->setGeometry(
        int(r.x()      * sx),
        int(r.y()      * sy),
        int(r.width()  * sx),
        int(r.height() * sy));

    w->setProperty("_scaled", true);
}

void UIScale::scaleTree(QWidget *root)
{
    scale(root);

    const auto widgets = root->findChildren<QWidget *>();

    for (QWidget *w : widgets)
    {
        qDebug().noquote()
        << QString("%1")
              .arg(w->objectName());
        scale(w);
    }
}

 

해당 위젯의 showEvent()를 오버라이드 해서 사용한다.

scaleTree()만 실행해도 잘된다.(어짜피 tree에서 순회하면서 쭈욱 여는거라)

그런데 widget 들은 확대되서 잘 나오는데

stylesheet에서 background로 박아둔 녀석도 같이 확대되서 이상하게 작동하는 지라

스타일시트 엔진(?)은 따로 움직여서 손을 봐줘야 한다고.

void cycle::showEvent(QShowEvent *event)
{
    qDebug() << "helo";
    UIScale::scaleTree(this);
    this->update();
    this->repaint();

    QString ss = this->styleSheet();
    this->setStyleSheet("");
    this->setStyleSheet(ss);
}

[링크 : https://chatgpt.com/share/6a420896-c94c-83e8-9459-3c016987a64f]