如何在屏幕上居中Qt主变形?

问题描述 投票:7回答:6

我在mainform的构造函数中尝试过这些:

QRect desktopRect = QApplication::desktop()->availableGeometry(this);
move(desktopRect.center() - frameGeometry().center());

QRect desktopRect = QApplication::desktop()->availableGeometry(this);
move(desktopRect.center() - rect().center());

但是两者都将表格的右下角放在屏幕的中心附近,而不是将表格居中。有任何想法吗?

qt qt4 qt4.6
6个回答
10
投票

我在mainform的构造函数中尝试过这些

这可能就是问题所在。此时您可能没有有效的几何信息,因为该对象不可见。

当对象首次构建时,它基本上位于(0,0),它具有预期的(width,height),如下:

frame geometry at construction:  QRect(0,0 639x479) 

但是,在显示之后:

frame geometry rect:  QRect(476,337 968x507) 

因此,您还不能依赖您的frameGeometry()信息。

编辑:据说,我认为你可以根据需要轻松移动它,但为了完整性我在Patrice's code下降,这不依赖于框架几何信息:

QRect desktopRect = QApplication::desktop()->availableGeometry(this);
QPoint center = desktopRect.center();

move(center.x() - width() * 0.5, center.y() - height() * 0.5);

4
投票

move函数(参见QWidget doc)将一个QPoint或两个int作为参数。这对应于Widget左上角的坐标(相对于其父级;此处为OS Desktop)。尝试:

QRect desktopRect = QApplication::desktop()->availableGeometry(this);
QPoint center = desktopRect.center();

move(center.x()-width*0.5, center.y()-height*0.5);

1
投票
#include <QStyle>
#include <QDesktopWidget>

window->setGeometry(
    QStyle::alignedRect(
        Qt::LeftToRight,
        Qt::AlignCenter,
        window->size(),
        qApp->desktop()->availableGeometry()
    )
);

https://wiki.qt.io/How_to_Center_a_Window_on_the_Screen


1
投票

availableGeometry()已被弃用。

move(pos() + (QGuiApplication::primaryScreen()->geometry().center() - geometry().center()));

0
投票

PyQT Python版

# Center Window
desktopRect = QApplication.desktop().availableGeometry(self.window)
center = desktopRect.center();
self.window.move(center.x()-self.window.width()  * 0.5,
                 center.y()-self.window.height() * 0.5);   

-1
投票

另一个解决方案,假设有问题的窗口是800×800:

QRect rec = QApplication::desktop()->availableGeometry();
move(QPoint((rec.width()-800)/2, (rec.height()-800)/2));
© www.soinside.com 2019 - 2024. All rights reserved.