QT学习笔记-程序启动时让窗口屏幕居中显示

QT学习笔记-程序启动时让窗口屏幕居中显示


在使用QT进行GUI开发时,通常希望主窗口启动时位于屏幕居中位置,原来在Winform开发时Form有个StartPosition属性,直接设置就行,在QT Creator的设计器中找了找没找到,不过我们通过代码实现,具体如下:

#include <QApplication>
#include <QDebug>
#include <QScreen>
#include <QDesktopWidget>

#include "mainwindow.h"

int main(int argc, char *argv[])
{
    
    
    QApplication a(argc, argv);
    MainWindow w;
    
    //以下为屏幕居中实现
    int currentScreen = a.desktop()->screenNumber(&w);      //程序坐在屏幕编号
    QScreen* screen = QGuiApplication::screens().at(currentScreen);
    QRect rect = screen->geometry();
    w.move((rect.width() - w.width()) / 2, (rect.height() - w.height()) / 2);       //移动到所在屏幕中间

    w.show();

    return a.exec();
}

猜你喜欢

转载自blog.csdn.net/zlbdmm/article/details/129625391