qt自动设置屏幕大小的代码
时间: 2024-12-06 20:26:37 浏览: 33
在Qt中,如果你想要让窗口自动适应屏幕大小,可以使用`QMainWindow`的`setFixedSize()`和`adjustSize()`方法。下面是一个简单的示例代码:
```cpp
#include <QApplication>
#include < QMainWindow >
#include < QVBoxLayout >
class MyWindow : public QMainWindow {
public:
explicit MyWindow(QWidget *parent = nullptr)
: QMainWindow(parent)
{
// 设置窗口的基本属性
setWindowTitle("Auto Size Example");
// 创建一个垂直布局管理器
QVBoxLayout *layout = new QVBoxLayout();
// 添加一些内容到布局,例如 QLabel 或者 QWidget
QLabel *label = new QLabel("This is a dynamic label", this);
layout.addWidget(label);
// 将布局设置为主窗口的内容
setCentralWidget(layout);
// 初始设定窗口大小为屏幕大小
setFixedSize(QDesktopWidget().screenGeometry(this).size());
// 当窗口移动或调整大小时,自动调整布局以保持窗口内容比例不变
resizeEvent(e) {
layout->setContentsMargins(0, 0, 0, 0); // 取消默认边距
adjustSize(); // 自动调整窗口大小
}
};
int main(int argc, char **argv)
{
QApplication app(argc, argv);
MyWindow window;
window.show();
return app.exec();
}
```
在这个例子中,窗口会根据其所在屏幕的大小初始化,并且当窗口在屏幕上移动或用户手动改变其大小时,窗口内的内容会按比例调整。
阅读全文
相关推荐


















