QT 获取有多个显示器的分辨率

如果要将一个程序窗体在电脑屏幕上做布局,那么首先得获取电脑屏幕的分辨率,当前屏幕大小通过以下代码即可获取:

	//获取当前屏幕大小
	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);
}
  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值