如果要将一个程序窗体在电脑屏幕上做布局,那么首先得获取电脑屏幕的分辨率,当前屏幕大小通过以下代码即可获取:
//获取当前屏幕大小
QScreen *screen = QGuiApplication::primaryScreen();
QRect screenRect = screen->availableVirtualGeometry();
int nWidth = screenRect.width();
int nHeight = screenRect.height();
但是这里有一个坑,如果别人的主机连接了多个显示器,那以上的方式就不可取了。得通过以下方式实现。
通过 QRect screenRect = QApplication::desktop()->screenGeometry(this) 获取屏幕,参数this是一个QWidget*。
这里有几点要明白:
1、以上代码获取的屏幕是窗体所在的屏幕。
2、整个显示器的原点坐标(0, 0)为主显示器的左上角。
3、如果两个显示器设置的分辨率一样,宽度为1920,把2作为主屏幕,1作为扩展屏幕,那么1的左上角坐标即为(-1920, 0)。
4、通过screenRect.x()和screenRect.y()得到的数值为屏幕原点坐标的x,y。
5、显示器分屏后的编号与这里获取到的一点关系都没有。
明白以上几个要点,下面很轻松的可以计算出窗体在屏幕上的停靠位置
//ViewForm为窗体类,nDockLocation布局,停靠位置为上下左右居中
void ViewForm::ResetWindow(int nDockLocation)
{
QRect screenRect = QApplication::desktop()->screenGeometry(this);
double dNewX = this->x();
double dNewY = this->y();
//移动窗体
switch (nDockLocation)
{
case EN_TOPLAYOUT:
dNewX = screenRect.x() + (screenRect.width() - nWidth) * 0.5;
dNewY = g_dDistance;
break;
case EN_BUTTOMLAYOUT:
dNewX = screenRect.x() + (screenRect.width() - nWidth) * 0.5;
dNewY = screenRect.height() - nHeight - g_dDistance;
break;
case EN_LEFTLAYOUT:
dNewX = screenRect.x() + g_dDistance;
dNewY = (screenRect.height() - nHeight) * 0.5;
break;
case EN_RIGHTLAYOUT:
dNewX = screenRect.x() + screenRect.width() - nWidth - g_dDistance;
dNewY = (screenRect.height() - nHeight) * 0.5;
break;
}
this->move(dNewX,dNewY);
}