Qml自编RowLayout与ColumnLayout控件的实现

2025-10-18 17:43:33

1、使用方法一:

     默认没参数的会前后没有间距,控件与控件之间等分间距。

Qml自编RowLayout与ColumnLayout控件的实现

2、使用方法二:

     有一些情况就是,需要边距与控件-控件等分的间距,使用rowInterval参数,为1时所有间距等分。

Qml自编RowLayout与ColumnLayout控件的实现

3、使用方法三:

       当rowInterval为指定参数时,即功能为控件第一个与最后一个控件与边框的距离,其余控件之间距离等分,说起来有点复杂,还是看图吧。

      可以看到一个rowInterval为20,一个为60的效果与边框的距离都不一样,在特定场合下使用特别有用,比如用于布局标题栏。

Qml自编RowLayout与ColumnLayout控件的实现

Qml自编RowLayout与ColumnLayout控件的实现

4、使用方法三:

      以上的布局可能也不适合你的使用,那就使用arrayWidthSpacing参数吧。

arrayWidthSpacing参数主要用来指定控件与控件之间的距离的,使用这个选项可以大大缩短你繁琐的布局时间,笔者在开发产品过程中使用得最多的一种布局方式了。

      参数需要这样使用,比喻有三个控件,他们间距分别为20,30,那么arrayWidthSpacing应该这样表示: arrayWidthSpacing: [20, 30],多个控件以此类推。

      图示为对比,一个是三个控件布局,一个是四个控件布局。

Qml自编RowLayout与ColumnLayout控件的实现

Qml自编RowLayout与ColumnLayout控件的实现

5、使用方法三:

      当然你也可以使用全为0的设置。

Qml自编RowLayout与ColumnLayout控件的实现

6、这时候也是要讲解RowLayout的实现。

      这里用到的时一个概念,children,先看图片,由于图片显示有限,截取一部分核心代码显示。

      1. 上文中rowInterval参数与arrayWidthSpacing都是在这里产生的,他们使用是有两者只能使用一,看图片rowProgram()函数即可看出;

      2. Component.onCompleted: { rowProgram()} 相当于C++的构造函数,当外层控件使用RowLayout是即调用进行函数执行;

      3. widthCount()与heightCount()均为设置RowLayout的默认大小。

Qml自编RowLayout与ColumnLayout控件的实现

7、    这里这种将rowProgram()函数的实现,

   function rowProgram() {        

        if (arrayWidthSpacing.length)            

               selectInterval()//该函数为arrayWidthSpacing函数指定间距执行函数。

           else {           

               if (rowInterval === 0)                

                       notBeforeAndAfterInterval()//该函数为rowInterval距离边框间距为零,控件与控件之间等分间距。

               else if (rowInterval === 1)               

                       equalSpacing(); //该函数为rowInterval等分间距。

               else                

                       selectBeforeAndAfterInterval() //该函数为rowInterval之间边框间距,其余控件间距等分。

       }    

  }

Qml自编RowLayout与ColumnLayout控件的实现

8、     以下为equalSpacing()函数的实现,其余函数功能实现类似,有兴趣的可以研究。

    1. index是供遍历children的控件所使用的;

    2. widthCount这是计算所有要布局的控件的宽度;

    3. widthInterval则是保存计算到等分间距的值;

    4. 怎么计算widthInterval?

    widthInterval = (rowLayout.width - widthCount)/(2+(rowLayout.children.length - 1));

   这里(2+(rowLayout.children.length - 1))笔者可能不懂了,为什么要加2?因为要计算前后距离边框的值,一前加一后就是要加2咯。

    5. 以下要来最难的了,要水平布局,当然要设置X的坐标值,看以下代码时如何设置x的坐标值的以致等分控件间距的实现。

   for (index = 0; index < rowLayout.children.length; index++) {           

         rowLayout.children[index].x = (index + 1)*widthInterval + tempWidth;   

         tempWidth += rowLayout.children[index].width;            

        rowLayout.children[index].y = (rowLayout.height - rowLayout.children[index].height)/2;       

   }

   rowLayout.children[index].x 用与遍历设置x的坐标值;

   tempWidth += rowLayout.children[index].width用于保存布局的控件的宽度; 

   rowLayout.children[index].y则是垂直居中控件。

   

Qml自编RowLayout与ColumnLayout控件的实现

9、源代码实现(RowLayout与ColumnLayout)

http://download.csdn.net/detail/nicai_xiaoqinxi/9714022

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢