Andrea993
Andrea993

Reputation: 693

Qt Android. Get device screen resolution

I'm developing in qt 5.3 on android device. I can't get the screen resolution. With the old qt 5 version this code worked:

QScreen *screen = QApplication::screens().at(0);
largh=screen->availableGeometry().width();
alt  =screen->availableGeometry().height();

However now it doesn't work (returns a screen size 00x00). Is there another way to do it? thanks

Upvotes: 5

Views: 7414

Answers (3)

Zeus
Zeus

Reputation: 432

Size holds the pixel resolution

screen->size().width()
screen->size().height();

Whereas, availableSize holds the size excluding window manager reserved areas...

screen->availableSize().width()
screen->availableSize().height();

More info on the QScreen class.

Upvotes: 6

SRedouane
SRedouane

Reputation: 508

for more information, screen availableSize is not ready at the very beginning, so you have to wait for it, here is the code:

Widget::Widget(QWidget *parent){
...   
QScreen *screen = QApplication::screens().at(0);
connect(screen, SIGNAL(virtualGeometryChanged(QRect)), this,SLOT(getScreen(QRect)));
}

void Widget::getScreen(QRect rect)
{
    int screenY = screen->availableSize().height();
    int screenX = screen->availableSize().width();
    this->setGeometry(0,0,screenX,screenY);
}

Upvotes: 2

Ioan Paul Pirau
Ioan Paul Pirau

Reputation: 2833

I found that there are several ways to obtain the device resolution, each outputs the same results and thankfully works across all Os-es supported by Qt...

1) My favorite is to write a static function using QDesktopWidget in a reference class and use it all across the code:

QRect const CGenericWidget::getScreenSize()
{
    //Note: one might implement caching of the value to optimize processing speed. This however will result in erros if screen resolution is resized during execution
    QDesktopWidget scr;

    return scr.availableGeometry(scr.primaryScreen());
}

Then you can just call across your code the function like this:

qDebug() << CGenericWidget::getScreenSize();

It will return you a QRect const object that you can use to obtain the screen size without the top and bottom bars.

2) Another way to obtain the screen resolution that works just fine if your app is full screen is:

QWidget *activeWindow = QApplication::activeWindow();
m_sw = activeWindow->width();
m_sh = activeWindow->height();

3) And of course you have the option that Zeus recommended:

QScreen *screen = QApplication::screens().at(0);
largh=screen->availableSize().width();
alt  =screen->availableSize().height();

Upvotes: 1

Related Questions