如何集中QMainWindow?

时间:2017-12-26 03:40:44

标签: c++ windows qt

我正在使用Qt,但我不知道如何将QMainWindow窗口居中。我写了这段代码,但它不起作用。提前谢谢。

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

我明白了:

enter image description here

4 个答案:

答案 0 :(得分:2)

这些功能已过时:

QApplication::desktop()->screenGeometry()
QApplication::desktop()->availableGeometry()
QDesktopWidget::screen()

改为使用QScreen:

#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QScreen>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    move(QGuiApplication::screens().at(0)->geometry().center() - frameGeometry().center());
}

答案 1 :(得分:1)

我在某处看到一个更短的解决方案:

show();
move(
    QApplication::desktop()->screen()->rect().center()
    - frameGeometry().center()
);

但是,由于某些奇怪的原因,窗口仍未完全显示在中心位置。

答案 2 :(得分:0)

谢谢大家。我已经使用此代码解决了我的问题。

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();

我明白了:

enter image description here

答案 3 :(得分:-2)

size()方法获取窗口大小。

QDesktopWidget *desktop = QApplication::desktop();
int screenWidth, width;
int screenHeight, height;
int x, y;
QSize windowSize;
QRect rec = desktop->screenGeometry();
screenWidth = rec.width(); // get width of screen
screenHeight = rec.height(); // get height of screen

windowSize = size(); // size of our application window
width = windowSize.width();
height = windowSize.height();

// little computations
x = (screenWidth - width) / 2;
y = (screenHeight - height) / 2;

// move window to desired coordinates
move ( x, y );

有用的链接:http://www.qtcentre.org/threads/3399-set-QMainWindow-in-the-center-of-my-desktop