
QScreen 或 QDesktopWidget 获取屏幕的分辨率。#include <QApplication>
#include <QMainWindow>
#include <QScreen>
#include <QDesktopWidget>
class MainWindow : public QMainWindow
{
public:
MainWindow()
{
// 获取屏幕大小
QRect screenGeometry = QGuiApplication::primaryScreen()->geometry();
int screenWidth = screenGeometry.width();
int screenHeight = screenGeometry.height();
// 设置窗口大小为屏幕大小
resize(screenWidth, screenHeight);
// 禁止调整窗口大小
setFixedSize(size());
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}QGuiApplication::primaryScreen()->geometry() 获取主屏幕的分辨率。QRect screenGeometry 包含屏幕的宽度和高度。resize(screenWidth, screenHeight) 将窗口大小设置为屏幕的分辨率。setFixedSize(size()) 将窗口的大小设置为固定大小,用户无法调整窗口大小。如果希望窗口在启动时适应屏幕大小,但保留窗口的边框(例如,窗口标题栏和边框),可以通过减去边框的大小来调整窗口大小。例如:
QRect screenGeometry = QGuiApplication::primaryScreen()->geometry();
int screenWidth = screenGeometry.width();
int screenHeight = screenGeometry.height();
// 减去窗口边框的大小(根据需要调整)
int frameWidth = style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
int titleBarHeight = style()->pixelMetric(QStyle::PM_TitleBarHeight);
resize(screenWidth - 2 * frameWidth, screenHeight - frameWidth - titleBarHeight);如果希望窗口在启动时全屏显示(无边框),可以使用 setWindowState(Qt::WindowFullScreen),但这与“禁止调整窗口大小”的需求略有不同。
通过以上方法,你可以实现窗口在启动时自动调整为适应屏幕大小,并且用户无法调整窗口大小。