qt - 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
功能起始位置在左上角,这是我的问题,我该如何解决?
解决方案
我编辑了你的一些代码,你的问题得到了解决:
要在中心显示消息框,您只需将窗口设置为父窗口
在主窗口.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();
}
输出 :
推荐阅读
- node.js - Intellisense 不适用于使用 NPM 安装的软件包
- javascript - 如何将 lambda 函数转换为 next.js api 友好函数?
- spring - 使用 OAuth2 客户端 + 资源服务器的网关中的授权不起作用
- docker - 运行添加组/添加用户。获取:选项 s 不明确(shell、系统)错误
- c - 实时数据库不显示来自 pzem-004t 的数据
- node.js - 在centos上安装带有sequelize的nodejs时出错
- javascript - js等待循环,承诺完成
- java - 如何在 Eclipse 中创建 svg 文件
- reactjs - 当我刷新 NextJS 动态路由页面时,ID 消失了
- html - 如何根据移动视图重新排序引导列