qt QHBoxLayout详解

QHBoxLayout 是 Qt 框架中用于创建水平布局的类。它将子控件以横向的方式排列,并自动调整大小,以适应父窗口的尺寸变化。

重要方法

  • QHBoxLayout(QWidget *parent = nullptr):创建一个 QHBoxLayout 对象,并指定其父窗口部件。

  • **addWidget(QWidget *widget, int stretch = 0, Qt::Alignment alignment = 0):**向布局中添加一个控件。

  • **addLayout(QLayout *layout, int stretch = 0):**向布局中添加另一个布局。

  • **addSpacerItem(QSpacerItem *spacer):**向布局中添加一个间隔项,用于控制空间分配。

  • **removeWidget(QWidget *widget):**从布局中移除指定的控件。

  • **count() const:**返回布局中控件的数量。

  • **itemAt(int index) const:**返回指定索引处的布局项。

  • **setStretch(int index, int stretch):**设置指定控件的伸缩因子,控制其在布局中占用的空间比例。

  • **setSpacing(int spacing):**设置控件之间的间距。

  • **setContentsMargins(int left, int top, int right, int bottom):**设置布局的边距。

  • insertWidget(int , QWidget *, int , Qt::Alignment ):**在布局的指定位置插入一个子控件。

    #include <QApplication>
    #include <QWidget>
    #include <QHBoxLayout>
    #include <QPushButton>
    #include <QLineEdit>
    #include <QLabel>

    class MyWidget : public QWidget {
    public:
    MyWidget() {
    QHBoxLayout *layout = new QHBoxLayout(this);

    复制代码
          QLabel *label = new QLabel("Name:", this);
          layout->addWidget(label);
    
          QLineEdit *lineEdit = new QLineEdit(this);
          layout->addWidget(lineEdit);
    
          QPushButton *button = new QPushButton("Submit", this);
          layout->addWidget(button);
    
          layout->setSpacing(10); // 设置控件间距
          layout->setContentsMargins(5, 5, 5, 5); // 设置边距
    
          setLayout(layout);
      }

    };

    int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    复制代码
      MyWidget widget;
      widget.resize(300, 100);
      widget.show();
    
      return app.exec();

    }

觉得有帮助的话,打赏一下呗。。

相关推荐
带土110 分钟前
5. QT之Q_OBJECT详解
开发语言·qt
leon_zeng011 小时前
Qt Modern OpenGL 入门:从零开始绘制彩色图形
开发语言·qt·opengl
会飞的胖达喵11 小时前
Qt CMake 项目构建配置详解
开发语言·qt
寻找华年的锦瑟16 小时前
Qt-FFmpeg案例(0基础,包含环境配置)
开发语言·qt·ffmpeg
共享家952719 小时前
QT-界面优化(上)
开发语言·qt
__BMGT()20 小时前
参考文章资源记录
开发语言·c++·qt
lqj_本人21 小时前
鸿蒙原生与Qt混合开发:性能优化与资源管理
qt·harmonyos
lqj_本人21 小时前
鸿蒙Qt字体实战:消灭“豆腐块“乱码与自定义字体加载
qt·华为·harmonyos
大牙Adela21 小时前
在Mac上通过Multipass虚拟机中的Ubuntu系统使用Graphviz工具
c语言·qt·ubuntu·macos·multipass·graphviz
Wallace Zhang1 天前
PySide6 + QML - 调试日志01 -告别打印log中文乱码,快速且简单地解决
qt·pyside6·qml