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

    }

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

相关推荐
范特西.i5 天前
QT聊天项目(8)
开发语言·qt
枫叶丹45 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
十五年专注C++开发5 天前
Qt deleteLater作用及源码分析
开发语言·c++·qt·qobject
kangzerun5 天前
SQLiteManager:一个优雅的Qt SQLite数据库操作类
数据库·qt·sqlite
金刚狼885 天前
qt和qt creator的下载安装
开发语言·qt
追烽少年x5 天前
Qt中使用Zint库显示二维码
qt
谁刺我心5 天前
qt源码、qt在线安装器镜像下载
开发语言·qt
金刚狼885 天前
在qt creator中创建helloworld程序并构建
开发语言·qt
扶尔魔ocy6 天前
【转载】QT使用linuxdeployqt打包
开发语言·qt
YxVoyager6 天前
在VS2017中使用Qt的foreach宏,IntelliSense无法正确识别函数定义
c++·qt