Problem with DPI and QIcon
-
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%
scale 125%
scale 150%
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%)
(DPI100%)
How i could fix this dpi problem?
-
Multiply your rect() with the devicePixelRatio() of your widget: https://doc.qt.io/qt-6/qpainter.html#drawing-high-resolution-versions-of-pixmaps-and-images
-
@Christian-Ehrlicher what rect the QPainter path rect? and how do you multiply a rect? only its width/height?
-
@Kattia said in Problem with DPI and QIcon:
what rect the QPainter path rect?
The one you pass to QIcon::paint()
and how do you multiply a rect? only its width/height?
rect().size() * devicePixelRatio()