多显示器屏幕上的应用程序窗口和中心放置

时间:2013-05-06 09:50:49

标签: qt desktop-application qmainwindow

我有一个QMainWindow,由另一个应用程序启动。

问题是,在多监视器设置中,启动QMainWindow的应用程序可能位于第3个屏幕上,但我的窗口将始终在第一个屏幕上启动。

我通过以下方式解决了这个问题......

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

现在,如何在屏幕中央启动此窗口。 d.center()不是正确的方法,因为窗口的顶部将从中心点发射,因此它将被遮挡。

请告知。

1 个答案:

答案 0 :(得分:3)

也许尝试这样的事情:

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());
}

和用法:

CenterToScreen(this);  // or CenterToScreen(mainWin);