Qt设置每次运行弹窗显示屏幕中央
要确保Qt应用程序中的弹出窗口每次都显示在屏幕的中央,您可以使用以下方法:
使用QMessageBox的move方法手动设置窗口位置:
#include <QApplication>
#include <QMessageBox>
#include <QDesktopWidget>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMessageBox messageBox;
messageBox.setText("这是一个居中的弹出框");
messageBox.exec();
// 获取屏幕的几何信息
QDesktopWidget *desktop = QApplication::desktop();
int screenWidth = desktop->width();
int screenHeight = desktop->height();
// 计算弹窗的中心位置
int x = (screenWidth - messageBox.width()) / 2;
int y = (screenHeight - messageBox.height()) / 2;
// 设置弹窗的位置
messageBox.move(x, y);
return app.exec();
}
上述代码中,我们首先创建了一个QMessageBox,然后获取了屏幕的宽度和高度,计算出弹窗应该显示的中心位置,最后使用move方法设置弹窗的位置。
您还可以自定义一个继承自QMessageBox的子类,然后在子类的构造函数中设置窗口位置。这样,每次创建该子类的对象时,窗口都会自动居中显示。
无论使用哪种方法,确保在显示窗口之前设置窗口的位置,以便窗口在显示时处于屏幕的中央位置。