To solve the background

In the process of a project, the company asked me to do the high-resolution screen adaptation, which was to make the software we developed support 4K screen display. I began to search for information on Baidu, and many blogs gave the answer as follows:

# if (QT_VERSION > = QT_VERSION_CHECK,6,0 (5) QApplication: : setAttribute (Qt: : AA_EnableHighDpiScaling); #endif QApplication a(argc, argv);

 

 

To solve the process

I did the same and, yes, Qt did adjust the size of the window and component to screen adaptation, but the font size inside the component didn’t change, so it looked like this:



 

The solution

Doesn’t it look incongruous, doesn’t it look ugly, but there’s no way. If you have to ask me to explain it to you, here it is: The reason is that the DPI calculation of Qt is wrong, which will lead to different sizes of Qt on different platforms. The solution is to set the DPI of Qt, which is calculated according to the relationship between the physical length or width of the display and the resolution. Therefore, let’s reset the PointSize of Qt font, once. That will solve the problem. Don’t talk nonsense directly on the code:

# if (QT_VERSION > = QT_VERSION_CHECK,6,0 (5) QApplication: : setAttribute (Qt: : AA_EnableHighDpiScaling); #endif QApplication a(argc, argv); QFont font = a.font(); font.setPointSize(10); // This value is self-adjusting. If the font does not change, increase the value in setPointSize().

When you set the value in setPointSize() to a larger value, you will notice that the display works fine, as shown in the figure below:



 

 

The final code

Now, the font size is normal, but if you use 1080P, the font size will be even larger, because you are in 4K screen, so it will look normal, so what we should do next, is simple, let setpointSize () adjust itself according to the system, the problem is solved, no more, continue with the code:

# if (QT_VERSION > = QT_VERSION_CHECK,6,0 (5) QApplication: : setAttribute (Qt: : AA_EnableHighDpiScaling); #endif QApplication a(argc, argv); Const float DEFAULT_DPI = 96.0; HDC screen = GetDC(NULL); FLOAT dpiX = static_cast<FLOAT>(GetDeviceCaps(screen, LOGPIXELSX)); ReleaseDC(0, screen); float fontSize = dpiX / DEFAULT_DPI; QFont font = a.font(); font.setPointSize(font.pointSize()*fontSize); a.setFont(font);

Okay, so in that case, problem solved, adaptive problem solved Note: all of these operations need to be done inside the main function