cbuchart
cbuchart

Reputation: 11575

How to get screen number from saved geometry?

In order to restore last window geometry and state, I'm using a code similar to the one suggested in this Qt document:

void MainWindow::closeEvent(QCloseEvent *event)
{
  QSettings settings("MyCompany", "MyApp");
  settings.setValue("geometry", saveGeometry());
  QMainWindow::closeEvent(event);
}

void MainWindow::readSettings()
{
  QSettings settings("MyCompany", "MyApp");
  restoreGeometry(settings.value("geometry").toByteArray());
}

Looking at Qt's source code (qwidget.cpp), QWidget::saveGeometry and its sibling restoreGeometry are basically a serialization of geometry, screen number and window state.

Now, the application shows a splash screen during start up. I'd like to show such splash screen in the same monitor where the application's window will be displayed. I can set splash screen geometry based on QScreen geometry, but I need the screen number to complete this code:

const auto screens = qApp->screens();
const auto geometry = screens[/* screen number here */]->geometry();

How can I get only the screen number from the saved geometry?

Upvotes: 2

Views: 453

Answers (2)

Joel
Joel

Reputation: 149

Qt6 no longer has the aQpp->desktop() function. QDesktopWidget was deprecated.

The workaround I ended up using was saving off the MainWindow's screen's geometry and then passing the center of that geometry to QApplication::screenAt(). The QScreen returned is used in the QSplashScreen construstor.

void MainWindow::closeEvent( QCloseEvent *event )
{
  QSettings settings( "MyCompany", "MyApp" );
  settings.setValue( "geometry", saveGeometry() );
  settings.setValue( "screenGeometry", screen()->geometry() );
  QMainWindow::closeEvent( event );
}

Use the saved screen geometry in main:

int main()
{
  ...

  QSettings const settings;
  auto const screenGeometry{ settings.value( "MainWindow/screenGeometry" ).toRect() };

  QSplashScreen splashscreen{ *QApplication::screenAt( screenGeometry.center() ), {}, Qt::WindowStaysOnTopHint };

  splashscreen.show();
  QApplication::processEvents();

  ...
}

Upvotes: 1

cbuchart
cbuchart

Reputation: 11575

I've been able to solve the issue creating a fake QWidget (never shown), restoring its geometry, and using QDesktopWidget::screenNumber to get the monitor where it is supposed to be:

int MainWindow::getMonitorToShowSplashScreen() const
{
  QSettings settings("MyCompany", "MyApp");

  QWidget fake_widget;
  fake_widget.restoreGeometry(settings.value("geometry").toByteArray());

  return qApp->desktop()->screenNumber(&fake_widget);
}

Upvotes: 1

Related Questions