概述:Qt 窗口居中显示、窗体透明度设置等窗口布局技巧。
0x01、窗口居中显示
进行界面布局的时候,往往需要将界面显示在整个桌面的中心位置。
方法一:使用 QDesktopWidget(旧方法)
#include <QDesktopWidget>
// 在构造函数中
QDesktopWidget *desktop = QApplication::desktop();
move((desktop->width() - this->width()) / 2,
(desktop->height() - this->height()) / 2);方法二:使用 QScreen(推荐)
Qt 5.14+ 推荐使用 QScreen 替代 QDesktopWidget:
#include <QScreen>
// 获取主屏幕
QScreen *screen = QGuiApplication::primaryScreen();
// 计算居中位置
QRect screenGeometry = screen->availableGeometry();
int x = (screenGeometry.width() - this->width()) / 2;
int y = (screenGeometry.height() - this->height()) / 2;
move(x, y);方法三:使用 move 和 geometry
#include <QStyle>
#include <QApplication>
// Qt 内置居中方法
this->setGeometry(
QStyle::alignedRect(
Qt::LeftToRight,
Qt::AlignCenter,
this->size(),
qApp->desktop()->availableGeometry()
)
);方法四:在 showEvent 中设置
void MainWindow::showEvent(QShowEvent *event)
{
Q_UNUSED(event);
centerWindow();
}
void MainWindow::centerWindow()
{
QScreen *screen = QGuiApplication::primaryScreen();
QRect screenGeometry = screen->availableGeometry();
move((screenGeometry.width() - width()) / 2,
(screenGeometry.height() - height()) / 2);
}0x02、窗口透明度
设置窗口整体透明度
// 设置窗口透明度 (0.0 - 1.0)
this->setWindowOpacity(0.8); // 80% 不透明设置窗口背景透明
// 无边框窗口 + 透明背景
setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);注意:使用 Qt::WA_TranslucentBackground 时,需要重写 paintEvent 填充背景:
void MainWindow::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.fillRect(this->rect(), QColor(0, 0, 0, 150)); // 半透明黑色背景
}0x03、无边框窗口拖动
// 头文件
class MainWindow : public QMainWindow
{
// ...
protected:
void mousePressEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
private:
QPoint m_dragPosition;
};
// 源文件
void MainWindow::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
m_dragPosition = event->globalPos() - this->frameGeometry().topLeft();
event->accept();
}
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
if (event->buttons() & Qt::LeftButton) {
move(event->globalPos() - m_dragPosition);
event->accept();
}
}0x04、QWebEngineView 窗体问题
使用 QWebEngineView 控件后,如果父窗体设置了以下属性,会导致窗口不显示或半透明:
setWindowFlags(Qt::FramelessWindowHint);
setAttribute(Qt::WA_TranslucentBackground);解决方案
方法一:不使用 Qt::WA_TranslucentBackground
setWindowFlags(Qt::FramelessWindowHint);
// 注释掉这行
// setAttribute(Qt::WA_TranslucentBackground);方法二:设置 D3D9 选项
// 在 main.cpp 中设置环境变量
qputenv("QT_OPENGL", "angle");
// 或
qputenv("QT_WEBENGINE_DISABLE_SANDBOX", "1");方法三:使用自定义绘制
// 在 QWebEngineView 初始化后
setAttribute(Qt::WA_DontCreateNativeAncestors);
setAttribute(Qt::WA_NativeWindow);0x05、常用窗口属性
| 属性 | 说明 |
|---|---|
Qt::FramelessWindowHint | 无边框窗口 |
Qt::WindowStaysOnTopHint | 窗口置顶 |
Qt::WindowMinMaxButtonsHint | 显示最小化/最大化按钮 |
Qt::WindowCloseButtonHint | 显示关闭按钮 |
Qt::WA_TranslucentBackground | 透明背景 |
Qt::WA_DeleteOnClose | 关闭时删除 |
更新时间: 2026-03-27