首页 > 解决方案 > QMessageBox 相对于主窗口居中

问题描述

我有一个代码,当我单击按钮时会显示一个消息框。

构造函数:

window = new QWidget;
button = new QPushButton(window);
connect(button, &QPushButton::clicked, this, &MainWindow::clickButton);
setCentralWidget(window);

点击按钮():

void MainWindow::clickButton() {
    QMessageBox msg;
    msg.exec();
}

当我点击并运行代码时,小部件出现在屏幕中间,如果我点击按钮,消息框也会出现在屏幕中间,这就是它应该显示的方式。

当我拖动小部件并将其放置在其他位置时,我想将其定位到小部件的中心。

这给了我小部件的中心:window->mapToGlobal(window->rect().center()),但move功能起始位置在左上角,这是我的问题,我该如何解决?

标签: qt

解决方案


我编辑了你的一些代码,你的问题得到了解决:

要在中心显示消息框,您只需将窗口设置为父窗口

在主窗口.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QPushButton>
#include <QMessageBox>

QT_BEGIN_NAMESPACE
namespace Ui
{
class MainWindow;
}
QT_END_NAMESPACE

class MainWindow: public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = nullptr);

    ~MainWindow();

    void  clickButton();

private:
    Ui::MainWindow *ui;
    QWidget        *window;
    QPushButton    *button;
    QMessageBox    *msg;
};

#endif // MAINWINDOW_H

在 mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent):
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    window = new QWidget;
    button = new QPushButton(window);
    connect(button, &QPushButton::clicked, this, &MainWindow::clickButton);
    setCentralWidget(window);

    msg = new QMessageBox(window);
   
    //you can comment this line because for show message box in center you just need set window as it's parent
    msg->setGeometry(width() / 2.0, height() / 2.0, msg->width(), msg->height());
}

MainWindow::~MainWindow()
{
    delete ui;
}

void  MainWindow::clickButton()
{
    msg->exec();
}

输出 :

在此处输入图像描述


推荐阅读