当前位置: 首页 > ops >正文

【Qt mainwindow 】窗口在启动时自动调整为适应屏幕大小

实现步骤

  1. 获取屏幕大小:使用 QScreenQDesktopWidget 获取屏幕的分辨率。
  2. 设置窗口大小为屏幕大小:将窗口的大小设置为屏幕的分辨率。
  3. 禁止调整窗口大小:通过设置窗口的大小策略为固定大小。

示例代码

#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();
}

关键点说明

  1. 获取屏幕大小

    • 使用 QGuiApplication::primaryScreen()->geometry() 获取主屏幕的分辨率。
    • QRect screenGeometry 包含屏幕的宽度和高度。
  2. 设置窗口大小

    • 使用 resize(screenWidth, screenHeight) 将窗口大小设置为屏幕的分辨率。
  3. 禁止调整窗口大小

    • 使用 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),但这与“禁止调整窗口大小”的需求略有不同。

通过以上方法,你可以实现窗口在启动时自动调整为适应屏幕大小,并且用户无法调整窗口大小。

http://www.xdnf.cn/news/6951.html

相关文章:

  • 正则表达式与文本处理的艺术
  • Selenium-Java版(css表达式)
  • go语法大赏
  • btc交易所关键需求区 XBIT反弹与上涨潜力分析​​
  • 深入理解Java中的Minor GC、Major GC和Full GC
  • 组态王|组态王中如何添加西门子1200设备
  • 2.2.4
  • 【数据结构】1-3 算法的时间复杂度
  • Zookeeper 入门(二)
  • Elasticsearch基础篇-java程序通过RestClient操作es
  • HarmonyOS 影视应用APP开发--配套的后台服务go-imovie项目介绍及使用
  • [创业之路-361]:企业战略管理案例分析-2-战略制定-使命、愿景、价值观的失败案例
  • VueUse/Core:提升Vue开发效率的实用工具库
  • 牛客网NC210769: 字母大小写转换问题解析
  • 灵光一现的问题和常见错误1
  • c++ 仿函数
  • [Android] 奇妙扫描 V1.0.7
  • Linux系统之----重定向
  • 基于OpenCV的SIFT特征和FLANN匹配器的指纹认证
  • 泛微对接金蝶云星空实战案例技术分享
  • C++:C++内存管理
  • DeerFlow试用
  • 一周学会Pandas2 Python数据处理与分析-Pandas2数据添加修改删除操作
  • 使用python进行人员轨迹跟踪
  • 打造动效按钮平台 ButtonCraft:我和 CodeBuddy 的协作旅程
  • Nginx应用场景详解与配置指南
  • 源码安装gperftools工具
  • AI Agent | Coze 插件使用指南:从功能解析到实操步骤
  • 湖北理元理律师事务所:债务优化中的双维支持实践解析
  • 【HCIA】聚合VLAN