Reputation: 71
I'd like to change my Qt app's scale based on the resolution of my devices screen. I'm trying to determine the resolution of the device and set
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); // DPI support
QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); // HiDPI pixmaps
qputenv("QT_SCALE_FACTOR", scaleAsQByteArray);
before my QApplication is initialized, scaleAsQByteArray to 1 if it's around the size where my app looks decent, and > 1 depending on the difference between my intended resolution and the large display resolution of the current device.
This doesn't seem to be possible, at least from what I understand, as you need an initialized QApplication to get screen information, but I also can't use qputenv after that happens.
Does anyone have a solution for how I could go about setting the scale factor of a QApplication based on screen resolution? Or to simplify things, how to get the height and width of the device monitor before I initialize the QApplication window.
I was thinking about using a Scale {} in qml: hiding the main Window and showing the scaled version instead, though this might have some performance drawbacks, but that's basically what I'm trying to do.
Upvotes: 1
Views: 10108
Reputation: 71
I think I found a cheeky solution here. I ended up creating a throwaway QApplication just to get the width of the display, then set the scale factor and create the actual QApplication.
QApplication* temp = new QApplication(argc, argv);
QRect screenGeometry = QApplication::desktop()->screenGeometry();
double width = screenGeometry.width();
// assumes that the default desktop resolution is 720p (scale of 1)
int minWidth = 1280;
delete temp;
double scale = width / minWidth;
std::string scaleAsString = std::to_string(scale);
QByteArray scaleAsQByteArray(scaleAsString.c_str(), scaleAsString.length());
qputenv("QT_SCALE_FACTOR", scaleAsQByteArray);
QApplication app(argc, argv);
The app I'm work on has a ton of hard-sized objects, and I don't have the time to change everything to use layouts, so this is a great solution so far. Hope this helps someone else!
Upvotes: 4