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

    }

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

相关推荐
四维碎片18 分钟前
【Qt】乌班图安装Qt环境
开发语言·数据库·qt
蓝天智能1 小时前
QT MVC中Model的特点及使用注意事项
qt·mvc
woshigaowei51462 小时前
VS(QT)调用Matlab函数的方法
qt·matlab·vs
应用市场8 小时前
Qt插件机制实现动态组件加载详解
开发语言·qt
星源~9 小时前
Linux-Ubuntu系统安装特别指导
linux·qt·ubuntu·嵌入式开发·物联网设备
泽虞9 小时前
《Qt应用开发》笔记p3
linux·开发语言·数据库·c++·笔记·qt·面试
ajassi20009 小时前
开源 C++ QT QML 开发(十八)多媒体--音频播放
c++·qt·开源
XXYBMOOO9 小时前
如何自定义 Qt 日志处理并记录日志到文件
开发语言·数据库·qt
知南x10 小时前
【QT界面设计学习篇】qt快速开发技巧
开发语言·qt
宏笋10 小时前
Qt 绘制彩色文本,包括字符颜色分割、动画效果和渐变等多种花式效果
qt