QRect setGeometry primaryScreen move Qt 窗口居中显示 - #include &#34

📅 2026-11-30 👤 拼多多助力营销技巧 📂 pdd帮助力 👁️ 551 次阅读

Qt 窗口居中显示

引言一、窗体的setGeometry函数二、计算屏幕中心然后move三、借助QRect计算四、补充知识点

引言

窗口居中可以提供良好的视觉效果、突出重点内容、提升用户导航和操作的便利性,有助于改善用户体验。

Qt一般情况下,其Mainwindow或弹出的窗口默认就是居中的,但是也有特殊情况:这就需要将窗口移动到屏幕中心. 以下介绍几种常用的居中方式(大同小异):

一、窗体的setGeometry函数

setGeometry()可以调整窗口的QRect (位置和大小),调用QStyle::alignedRect可直接返回计算好的窗体相对屏幕居中的QRect,例程如下:

需要注意不要在resizeEvent() or moveEvent()调用setGeometry()函数,会导致无线循环

#include "mainwindow.h"

#include

#include

#include

int main(int argc, char *argv[])

{

QApplication a(argc, argv);

QWidget w;

w.setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter,

w.size(),

QGuiApplication::primaryScreen()->geometry()));

w.show();

return a.exec();

}

二、计算屏幕中心然后move

先获取屏幕的大小以及窗体的大小,然后手动计算窗口居中位置,使用move移动. 例程如下:

可参考 QT设置弹窗显示屏幕中央:https://blog.csdn.net/weixin_40921238/article/details/133378912

#include "mainwindow.h"

#include

#include

#include

int main(int argc, char *argv[])

{

QApplication a(argc, argv);

QWidget w;

// 获取屏幕的几何信息

QRect screenRect = QGuiApplication::primaryScreen()->geometry();

// 计算弹窗的中心位置

int x = (screenRect.width() - w.width()) / 2;

int y = (screenRect.height() - w.height()) / 2;

// 设置弹窗的位置

w.move(x, y);

w.show();

return a.exec();

}

三、借助QRect计算

借助QRect计算窗体和屏幕中心的位置偏移,然后进行移动.

可参考 Qt窗口的居中显示:https://www.bilibili.com/read/cv26794535/?jump_opus=1 Qt窗口屏幕居中显示:https://www.cnblogs.com/qq78292959/archive/2012/08/25/2655963.html

#include "mainwindow.h"

#include

#include

#include 拼多多帮助力入口

int main(int argc, char *argv[])

{

QApplication a(argc, argv);

QWidget w;

// 获取屏幕的几何信息

QRect screenRect = QGuiApplication::primaryScreen()->geometry();

// 计算居中位置

int x = (screenRect.width() - w.width()) / 2;

int y = (screenRect.height() - w.height()) / 2;

QPoint centerPoint = screenRect.center() - w.geometry().center();

// 设置弹窗的位置

w.move(w.pos() + centerPoint);

w.show();

return a.exec();

}

四、补充知识点

关于show和move,可以先move然后再show窗口就不会闪烁.

Qt推荐使用 QGuiApplication替代QApplication::desktop() 一般用QGuiApplication::primaryScreen()足以 QGuiApplication::screens()可以获取所有屏幕. 遍历代码如下:

QList screens = QGuiApplication::screens();

foreach (QScreen *screen, screens) {

qDebug() << "Screen geometry: " << screen->geometry();

qDebug() << "Screen available geometry: " << screen->availableGeometry();

qDebug() << "Screen logical DPI: " << screen->logicalDotsPerInch();

qDebug() << "Screen physical DPI: " << screen->physicalDotsPerInch();

qDebug() << "Screen scale factor: " << screen->devicePixelRatio();

}

QRect简述 QRect类使用整数精度定义平面中的矩形,通常表示为左上角(top() and left())和大小(width() and height())。

由于历史原因,bottom()和right()函数返回的值偏离了矩形的真正右下角:right返回left+width-1,bottome返回top+height-1。bottomRight函数返回的点也是如此。 建议使用x+width和y+height来找到真正的右下角,并避免使用right和bottom。另一种解决方案是使用QRectF:QRectF类使用坐标的浮点精度定义平面中的矩形,并且QRectF::right和QRectF::bottom函数确实返回右坐标和底坐标。

文章链接

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧