Search code examples
cssfontsqt4dpiqwebview

Differing DPI [font sizes] in QWebView compared to all other QWidgets?


I have a QWebView which displays some HTML content and I used CSS to style the text:

body { font-size: 10pt; }

The window with the QWebView also has a QTextEdit field, for which I have set the font like this:

QFont newFont;
newfont.setPointSize(10);
myEditField->setFont(newFont);

Unfortunately, the text displayed in the QWebView is slightly larger than the text displayed in the QTextEdit. I have a feeling that this has something to do with DPI settings being different in the QWebView.

Is there a way to get the same font sizes displayed for both the QWebView and the QTextEdit?

Thanks!


Solution

  • Explanation of this behavior has been given on the bugreports:

    It appears to be true that WebKit assumes 96 dpi as a fixed resolution. If this is how web content is designed then we have a problem changing that, because there are other people that expect WebKit to render web content like in web browsers. See also https://www.webkit.org/blog/57/css-units/

    They suggested two solutions:

    QWebView provides setZoomFactor and setTextMultiplier which I believe could be used to get the desired behaviour (matching the QWidget ).

    You can calculate zoom factor and text multiplier using current DPI:

    QWidget* window = QApplication::desktop()->screen();
    const int horizontalDpi = window->logicalDpiX(); 
    m_view->setZoomFactor(horizontalDpi / 96.0);
    

    Using QWebSettings::ZoomTextOnly you can apply zooming to the text only.