質問

I've a QMainWindow, which is launched by another application.

The problem is, in a multimonitor setup, the application launching my QMainWindow, might reside on the 3rd screen, but my window will always launch on the first.

I worked around this in the following way...

QDesktopWidget *m = new QDesktopWidget();
QPoint p= QCursor::pos();
int r= m->screenNumber(p); //get the screennumber where the mouse is
QRect d=m->screenGeometry(r);
QPoint l = d.center(); //not the correct solution
mainWin->move(l); //move the window to that screen
mainWin->show(); //launch

Now, how do I launch this window in the centre of the screen. d.center() is not the correct way, as the topleft of the window will launch from the centre point, so it will be obscured.

Kindly advise.

役に立ちましたか?

解決

Maybe try something like this:

void MainWindow::CenterToScreen(QWidget* widget) {
  if (!widget)
    return;
  QDesktopWidget* m = QApplication::desktop();
  QRect desk_rect = m->screenGeometry(m->screenNumber(QCursor::pos()));
  int desk_x = desk_rect.width();
  int desk_y = desk_rect.height();
  int x = widget->width();
  int y = widget->height();
  widget->move(desk_x / 2 - x / 2 + desk_rect.left(), desk_y / 2 - y / 2 + desk_rect.top());
}

and usage:

CenterToScreen(this);  // or CenterToScreen(mainWin);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top