DPI-independent UI design with QML

  • I've encountered this problem with Java Swing, and now I'm curious how this problem is/should be solved with QML.

    When you're designing a button or a toolbar, you're putting text onto it. Then some margins to make it look better. On Desktop computer, which still has around 96 DPI, you will make those margins 4 to 6 pixels. On 13" FullHD laptop you'll make that 8-10 pixels. And I have no idea what margin should there be on high-DPI android/iOS devices.

    So the question is, are QML margins measured in actual pixels, or to 1/72 of an inch (as in font design)? If they are measured in actual pixels - how do you overcome this problem?

    PS: links to documentation in case I missed them are appreciated.

  • Anyone? I found following articles:

    Which means that Qt+QML does support device-independent layouts, but there are absolutely no examples how to do it in QML. Someone on stackoverflow suggests to calculate scale factor in C++ part and multiply all dimensions to it, but that doesn't sound right.

  • This page may help you "How to create mobile games for different screen sizes and resolutions":http://v-play.net/doc/vplay-different-screen-sizes.html

  • In Qt 5.2 I use the following approach for mobile development with QML:

    qmlContext->setContextProperty("screenPixelDensity", QGuiApplication::primaryScreen()->physicalDotsPerInch());@


    @function dp(dpVal) {
    var px = Math.round(dpVal * (screenPixelDensity / 160));

    if(Qt.platform.os == "windows" || Qt.platform.os == "mac")
        return px*2;
        return px;


    All the sizes I specify with dp() function. F.ex. "width: dp(15)".
    This approach works good enough for me :)

  • Hi, you should multiply physicalDotsPerInch with devicePixelRatio instead of using the "if" in QML, that is more reliable and should result in the same value for mac and iOS (windows has set it to 1.0 though i guess). :)
    qmlContext->setContextProperty("screenPixelDensity", QGuiApplication::primaryScreen()->physicalDotsPerInch() * QGuiApplication::primaryScreen()->devicePixelRatio());

    Anyway I use a similar approach, just a few days ago I've written a post about that here in the forums somewhere.

  • Xander84, thanks for the tip but it doesn't really work for me. I develop mobile app and use windows/macos on non-retina displays just to make development faster. Standard 96dpi are to small and devicePixelRation is equal to 1 on non-retina, so I multiply by 2 to make everything bigger :)

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.