Reputation: 567
I'm using Qt but I don't know how to center a QMainWindow window. I wrote this code, but it doesn't works. Thanks in advance.
QRect screenGeometry = QApplication::desktop()->screenGeometry();
int x = (screenGeometry.width() - w->width()) / 2;
int y = (screenGeometry.height() - w->height()) / 2;
w->move(x, y); // w is a QMainWindow pointer
I get this:
Upvotes: 5
Views: 7762
Reputation: 1144
These functions are obsolete:
QApplication::desktop()->screenGeometry()
QApplication::desktop()->availableGeometry()
QDesktopWidget::screen()
Use QScreen instead:
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QScreen>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
move(screen()->availableGeometry().center() - frameGeometry().center());
}
Upvotes: 9
Reputation: 4609
from PySide2.QtCore import QRect, QPoint
from PySide2.QtWidgets import QApplication, QMainWindow
QApplication()
mainWindow = QMainWindow()
mainWindow.resize(1280, 720)
mainWindow.move(mainWindow.screen().geometry().center()
- QRect(QPoint(), mainWindow.frameGeometry().size()).center())
mainWindow.show()
QApplication.exec_()
frameGeometry()
may not have a zero top-left, so we only need the size.
Upvotes: 0
Reputation: 41
the following code works in the latest version of Qt 6.4.1
#include <QApplication>
#include <QScreen>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
int width = w.frameGeometry().width();
int height = w.frameGeometry().height();
QScreen *screen = a.primaryScreen();
int screenWidth = screen->geometry().width();
int screenHeight = screen->geometry().height();
w.setGeometry((screenWidth/2)-(width/2), (screenHeight/2)-(height/2), width, height);
w.show();
return a.exec();
}
Upvotes: 3
Reputation: 542
There's a shorter solution I saw somewhere:
show();
move(
QApplication::desktop()->screen()->rect().center()
- frameGeometry().center()
);
Yet, for some weird reason, the window still does not appear exactly at the center.
Upvotes: 0
Reputation: 567
Thank you to everybody. I already solved my problem, using this code.
w->setFixedSize(400, 400);
int width = w->frameGeometry().width();
int height = w->frameGeometry().height();
QDesktopWidget wid;
int screenWidth = wid.screen()->width();
int screenHeight = wid.screen()->height();
w->setGeometry((screenWidth/2)-(width/2),(screenHeight/2)-(height/2),width,height);
w->show();
I get this:
Upvotes: 2