High DPI cause wrong scaling of pixmaps

80 views Asked by At

I'm using Qt 6.5 on Windows 10, the pixmaps on my application are scaled differently according to the current DPI.

A minimal reproducible exxample:

Windows scale 100%

del_YcpVZze4Xo.png

scale 125%

del_KFwUNzwjVc.png

scale 150%

del_KkC7k6lJzQ.png

class Label : public QLabel
{
    Q_OBJECT
public:
    QIcon icon;
    Label(QWidget* parent = nullptr) : QLabel(parent){}
    void paintEvent(QPaintEvent* event) override
    {
        QPainter painter(this);
        painter.setRenderHint(QPainter::Antialiasing);
        painter.setRenderHint(QPainter::SmoothPixmapTransform);
        icon.paint(&painter, rect(), Qt::AlignCenter, QIcon::Normal, QIcon::On);
    }
};

inline QPixmap setRoundness(QPixmap pixmap, int roundness)
{
    QPainterPath path;
    qDebug() << pixmap.width() << pixmap.height();
    // Round the pixmap by 50%
    path.addRoundedRect(QRectF(0, 0, pixmap.width(), pixmap.height()), pixmap.width() / 2, pixmap.height() / 2);

    QPixmap roundedPixmap = QPixmap(pixmap.size());
    roundedPixmap.fill(Qt::transparent);
    QPainter painter(&roundedPixmap);
    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::SmoothPixmapTransform);
    painter.fillPath(path, Qt::black);
    painter.setCompositionMode(QPainter::CompositionMode_SourceIn);
    painter.drawPixmap(0, 0, pixmap);

    pixmap.save("test_1.png");
    roundedPixmap.save("test_2.png");
    return roundedPixmap;
}

class MainWindow : public QMainWindow
{
   Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr) : QMainWindow(parent), ui(new Ui::MainWindowClass())
{
      ui->setupUi(this);
      setStyleSheet("#centralWidget { background-color: rgba(80, 80, 80, 80); }");

      QIcon icon = QIcon("C:/Users/Katia/test.png"); // test.png => https://i.imgur.com/cZfWHkW.png
      QPixmap roundedPixmap = setRoundness(icon.pixmap(QSize(55, 55)), 50);

      Label* label = new Label;
      label->icon = roundedPixmap;
      QLabel* label_2 = new QLabel;
      label_2->setPixmap(roundedPixmap);

      QWidget* widget = new QWidget;
      QHBoxLayout* hLayout = new QHBoxLayout(widget);
      hLayout->addWidget(label);
      hLayout->addWidget(label_2);
      hLayout->setContentsMargins(0, 0, 0, 0);
      hLayout->setSpacing(30);

      setCentralWidget(widget);
      setContentsMargins(32, 32, 32, 32);
      return;
   }
}

Its a problem in the QPixmap and not in QPaintEvent because when i save roundedPixmap.save("test_2.png"); this is what i get:

(DPI 150%) x2.png

(DPI100%) x2.png

How i could fix this dpi problem?

1

There are 1 answers

0
Nome On

try this:

label_2->setPixmap(roundedPixmap.scaled(label2->size()));

Anyway I don't like to use QLabels to show images, because QLabel has properties you dont like: try myLabel.setEnabled(false)