Qt 窗口居中顯示
- 引言
- 一、窗體的setGeometry函數
- 二、計算屏幕中心然后move
- 三、借助QRect計算
- 四、補充知識點
引言
窗口居中可以提供良好的視覺效果、突出重點內容、提升用戶導航和操作的便利性,有助于改善用戶體驗。
- Qt一般情況下,其Mainwindow或彈出的窗口默認就是居中的,但是也有特殊情況:這就需要將窗口移動到屏幕中心. 以下介紹幾種常用的居中方式(
大同小異
):
一、窗體的setGeometry函數
setGeometry()
可以調整窗口的QRect
(位置和大小),調用QStyle::alignedRect
可直接返回計算好的窗體相對屏幕居中的QRect
,例程如下:
需要注意不要在resizeEvent() or moveEvent()調用
setGeometry()
函數,會導致無線循環
#include "mainwindow.h"
#include <QApplication>
#include <QStyle>
#include <QScreen>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 <QApplication>
#include <QStyle>
#include <QScreen>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 <QApplication>
#include <QStyle>
#include <QScreen>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()
可以獲取所有屏幕. 遍歷代碼如下:
- Qt推薦使用
QList<QScreen *> 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()
andleft()
)和大小(width()
andheight()
)。
- QRect簡述
由于歷史原因,bottom()和right()函數返回的值偏離了矩形的真正右下角:right返回left+width-1,bottome返回top+height-1。bottomRight函數返回的點也是如此。
建議使用x+width和y+height來找到真正的右下角,并避免使用right和bottom
。另一種解決方案是使用QRectF:QRectF類使用坐標的浮點精度定義平面中的矩形,并且QRectF::right和QRectF::bottom函數確實返回右坐標和底坐標。