PDA

View Full Version : QScreen size returning zero



alistair
31st July 2015, 01:33
Hi,

I am using the following function to return screen size:



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


I tested this code by making a push button and on the button click, it runs this code and it works. Although when I try putting this code in my constructor function, it keeps returning screenWidth = 0 and screenHeight = 0.



MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);

QScreen *screen = QApplication::screens().at(0);
screenWidth = screen->availableSize().width();
screenHeight = screen->availableSize().height();
}


Any help would be greatly appreciated, thank you :).

anda_skoa
31st July 2015, 09:32
From the description I would guess that the determination of the screen size requires some event based interaction between the application and the system.
The constructor of the main window is usually run before the event loop is started, so it might not have had a chance yet to do that.

You could try calling that code delayed using QTimer::singleShot() with a 0 timeout.

Cheers,
_

alistair
4th August 2015, 01:29
Hi, thank you for your help! This is how I got it to work. Also I don't know how to change the title of the thread to [solved] lol


void mainwindowWing::delay()
{
QTime dieTime= QTime::currentTime().addMSecs(1);
while (QTime::currentTime() < dieTime)
QCoreApplication::processEvents(QEventLoop::AllEve nts, 100);
}

mainwindowWing::mainwindowWing(QWidget *parent) :
QWidget(parent),
ui(new Ui::mainwindowWing)
{
ui->setupUi(this);
delay();
QTimer::singleShot( 0, this, SLOT( setupGUI()) );
}

anda_skoa
4th August 2015, 10:18
Are you sure you need that "delay" method?
The single shot time will already delay invocation of setupGUI to after the event loop has started processing events.

Cheers,
_

alistair
4th August 2015, 23:46
Yeah I understand although it works with it and does not work without it, haha :p

anda_skoa
5th August 2015, 10:38
Hmm.
Have you tried connecting to the QScreen's availableGeometryChanged() signal as the trigger?

If you need those values that might be a good idea anyway in case the geometry changes again.

Cheers,
_

ChrisW67
5th August 2015, 10:58
It seems likely that the application is not "connected" to a screen until the window is shown. Try looking at the values in the showEvent() handler.

Why do you need the screen geometry before your window is shown?