1.問題
需要對彈出的對話框相對進行居中,但無邊框對話框正常顯示會導致偏差了幾個相素。於是手動move的方法。大概代碼如下。思路是通過獲取當前窗口父窗口原點位置計算子窗口的偏移move達到居中的效果。然後在過程中發現了geometry()返回的值x,y比較怪異。
void AlignCenter(QWidget* parent)
{
if (!parent) return;
QRect pRect = parent->geometry();
int x, y;
if (parent->parent())
{
QPoint globPos = parent->mapToGlobal(QPoint(0, 0));
x = globPos.x() + pRect.width() / 2 - this->width() / 2;
y = globPos.y() + pRect.height() / 2 - this->height() / 2;
}
else
{
x = pRect.x() + pRect.width() / 2 - this->width() / 2;
y = pRect.y() + pRect.height() / 2 - this->height() / 2;
}
this->move(x, y);
}
2.geometry()函數
先上一段文檔,從文檔中可以看出是相對其父窗口的。並且排除了窗口邊框。但在實際過程中發現QDialog及其子類獲取的Rect的x及y座標並不是相對其父窗口的。
3.測試結論
如文檔所言,geometry相對於其父窗口而言對於QWidget是生效的。但QWidget和QDialog多個父子窗口嵌套的情況下.Dialog的geometry獲取的rect中的x,y始終是相對一屏幕左上向角的原點座標系。
附圖參考自網絡