Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在屏幕上居中显示Qt Main窗体?_Qt_Qt4_Qt4.6 - Fatal编程技术网

如何在屏幕上居中显示Qt Main窗体?

如何在屏幕上居中显示Qt Main窗体?,qt,qt4,qt4.6,Qt,Qt4,Qt4.6,我已经在mainform的构造函数中尝试过这些: QRect desktopRect = QApplication::desktop()->availableGeometry(this); move(desktopRect.center() - frameGeometry().center()); QRect desktopRect = QApplication::desktop()->availableGeometry(this); move(desktopRect.center

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

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

QRect desktopRect = QApplication::desktop()->availableGeometry(this);
move(desktopRect.center() - rect().center());
但两者都将窗体的右下角放在屏幕的中心,而不是窗体的中心。有什么想法吗?

移动函数(参见文档)采用一个QPoint或两个int作为参数。这对应于小部件左上角的坐标(相对于其父级;此处为操作系统桌面)。 尝试:

我在主窗体的构造函数中尝试过这些

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

当第一次构造对象时,它基本上位于
(0,0)
,预期的
(宽度、高度)
,如下所示:

frame geometry at construction:  QRect(0,0 639x479) 
但是,在展示之后:

frame geometry rect:  QRect(476,337 968x507) 
因此,您还不能依赖
frameGeometry()
信息

编辑:尽管如此,我认为您可以根据需要轻松地移动它,但为了完整性,我将插入不依赖于帧几何体信息的内容:

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

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

另一种解决方案,假设所讨论的窗口为800×800:

QRect rec = QApplication::desktop()->availableGeometry();
move(QPoint((rec.width()-800)/2, (rec.height()-800)/2));
#包括
#包括
窗口->设置几何体(
QStyle::alignedRect(
Qt::LeftToRight,
Qt::AlignCenter,
窗口->大小(),
qApp->desktop()->availableGeometry()
)
);
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);   
availableGeometry()
已弃用

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

移动(QGuiApplication::primaryScreen()->geometry().center()-rect().center())

我发现如果我在代码将其居中之前调用
this->resize(width\u I\u want,height\u I\u want)
,它可以工作。谢谢那很有趣。这会如何改变帧的几何结构?我不喜欢假设窗口的大小,尤其是在高DPI显示和移动设备不断变化的时代。
# 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);   
move(pos() + (QGuiApplication::primaryScreen()->geometry().center() - geometry().center()));